2017-08-19 54 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

相關問題