如何在我的类unique_ptr中提供自定义删除器?
How to provide custom deleter in my class unique_ptr?
我已经完成了我的unique_ptr:
template<class T, typename D = default_deleter<T> >
class unique_ptr
{
private:
T* _ptr;
D deleter;
public:
//Default constructor
explicit unique_ptr(void): _ptr(nullptr) { }
//Constructor with the provided pointer to manage
unique_ptr(T* p) throw() : _ptr(p), deleter(default_deleter<T>())
{ }
unique_ptr(T* p, D d) throw() : _ptr(p), deleter(d) { }
~unique_ptr(void) throw() // never throws
{
delete _ptr;
_ptr = nullptr;
}
这是一个default_deleter
template<typename T>
struct default_deleter
{
default_deleter() { }
template<typename _Up>
default_deleter(const default_deleter<_Up>&) { }
void operator()(T* p) const
{
delete p;
}
};
但是当我尝试使用自定义删除器时:
struct MyCustomDeleter {
void operator()(SomeResource* p) {
p->releaseResources();
delete p;
}
};
int main() {
unique_ptr<SomeResource, MyCustomDeleter> ptr1(new SomeResource(1));
我得到 调用"MyCustomDeleter::MyCustomDeleter(default_deleter("没有匹配函数
您始终使用默认删除器初始化unique_ptr,但代码中存在不一致。
template<class T, typename D = default_deleter<T> >
class unique_ptr
{
private:
T* _ptr;
D deleter; // you do not need this, since the type is known at c-t
public:
//Default constructor
explicit unique_ptr(void): _ptr(nullptr) { } // but no initialization of D
//Constructor with the provided pointer to manage
unique_ptr(T* p) throw() : _ptr(p), deleter(default_deleter<T>()) // wrong D !!
{ }
unique_ptr(T* p, D d) throw() : _ptr(p), deleter(d) { } // weird
};
您在编译时知道删除程序。
template<class T, typename D = default_deleter<T> >
class unique_ptr
{
private:
T* ptr_{nullptr};
public:
explicit unique_ptr(T* ptr) noexcept : ptr_(ptr) {}
unique_ptr() noexcept = default;
unique_ptr(const unique_ptr&) = delete;
unique_ptr(unique_ptr&& x) noexcept : ptr_(x.release()) {}
~unique_ptr() noexcept(noexcept(D(T*{}))) { reset(); }
void reset() noexcept(noexcept(D(T*{})))
{ if (ptr_) { D(ptr_); } ptr_ = nullptr; }
T* release() noexcept { auto p = ptr_; ptr_ = nullptr; return p; }
unique_ptr& operator= (const unique_ptr&) = delete;
unique_ptr& operator= (unique_ptr&& x) noexcept(noexcept(D(T*{})))
{ reset(); ptr_ = x.release(); return *this; };
// ... operators op*, ->, etc...
};
如果要在运行时指定删除程序,则它不应是模板参数。
相关文章:
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何使用 C 指针的自定义删除器创建unique_ptr?
- 在地图中使用自定义删除器存储unique_ptr
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 在unique_ptr<>中使用自定义删除程序 (curl_formfree())
- C++自定义删除运算符不能正常工作?
- 如何在我的类unique_ptr中提供自定义删除器?
- 无法使用带有 std::move 的自定义删除器插入 std::unique_ptr
- 未调用 std::unique_ptr 中的自定义删除器
- 如何为unique_ptr管理的数组编写自定义删除器?
- 适用于 std::unique_ptr 的内存高效自定义删除器?
- 用于unique_ptr的有状态自定义删除程序
- shared_ptr<>到数组自定义删除器(带make_shared)
- 为什么使用自定义删除器unique_ptr不适用于 nullptr,而shared_ptr则适用于 nullptr?
- 如何在自定义删除器的情况下复制unique_ptr
- 自定义删除器,用于shared_ptr<>给出"无上下文错误"
- 智能指针自定义删除器中的处理条件
- 为什么unique_ptr不能阻止自定义删除程序的切片?
- 提升共享指针自定义删除器示例
- 在shared_ptr的自定义删除器中检查 nullptr 是否有意义?