2017-08-19 59 views
0

我Implemeted一个我的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)'

+3

实现你自己的'unique_ptr'类的原因是什么?它解决了什么问题['std :: unique_ptr'](http://en.cppreference.com/w/cpp/memory/unique_ptr)没有解决? –

+0

对于初学者来说,请在[minimal,* complete *,example](https://stackoverflow.com/help/mcve)中发布* real *代码,以重现您的问题。 – WhozCraig

+0

它是真正的代码,将在稍后升级。 – Dsdsd

回答

0

您总是使用默认的删除器初始化您的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... 
}; 

如果你想在运行时指定一个删除器,它不应该是一个模板参数。

+0

中被删除,谢谢你的回答,我理解了这个问题并修正了它。 – Dsdsd

相关问题