2016-12-18 24 views
-3

我定義一個類,它有一個成員模板,到位的std :: shared_ptr的默認缺失者的:使用自定義刪除器中的shared_ptr

class DebugDelete { 
    public: 
     DebugDelete(std::ostream &s = std::cerr): os(s) { } 
     // as with any function template, the type of T is deduced by the compiler 
     template <typename T> void operator()(T *p) const 
     { 
      os << "deleting unique_ptr" << std::endl; 
      delete p; 
     } 
    private: 
     std::ostream &os; 
}; 

當我將它應用於下面的代碼,一些報告錯誤:

class A { 
    public: 
     // [Error] class 'A' does not have any field named 'r' 
     A(std::shared_ptr<std::set<int>> p): r(p) { } // 1: How can I use self-defined deleter to initialize r in constructor 
     A(int i): s(new std::set<int>, DebugDelete()) { } // 2: OK, what is the difference between this constructor and 3 
    private: 
     // [Error] expected identifier before 'new' 
     // [Error] expected ',' or '...' before 'new' 
     std::shared_ptr<std::set<int>> r(new std::set<int>, DebugDelete()); // 3: error 
     std::shared_ptr<std::set<int>> s; 
}; 
+1

我懷疑你收到的許多錯誤*與自定義刪除無關。當然,包括你問題中的實際錯誤信息(應該總是這樣做)會證實這一點。 – WhozCraig

+0

@WhozCraig我在代碼中添加了錯誤消息。 –

+0

您無法使用此語法在班級中初始化成員。嘗試使用大括號或相等的初始值設定項。 –

回答

0

在initialize_list您可以使用自定義刪除器一樣

shared_ptr<set<int>> r = shared_ptr<set<int>>(new set<int>, DebugDelete()); 

一nd你不應該使用一個shared_ptr來初始化另一個shared_ptr。

+0

我改變了我的代碼,如你所說,它編譯。但是我也定義了類A的成員函數 - 'void B(){shared_ptr > ptr(new set ,DebugDelete()); }' - '公共'和'私人'編譯。它怎麼發生的? –

+0

你的函數void B()是構造函數名爲ptr的shared_ptr。我的答案是分配一個成員變量。在C++ 11標準中,成員變量可以被初始化爲類內定義。例如:[link](http://en.cppreference.com/w/cpp/language/data_members) –

+0

nm的答案是初始化成員變量initialize_lists的另一種方法,請參閱:[link](https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists) –