繁体   English   中英

如何在我的类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... 
};

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM