如何在我的类unique_ptr中提供自定义删除器?

How to provide custom deleter in my class unique_ptr?

本文关键字:自定义 删除 ptr 我的 unique      更新时间:2023-10-16

我已经完成了我的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... 
};

如果要在运行时指定删除程序,则它不应是模板参数。