我定義一個類,它有一個成員模板,到位的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;
};
我懷疑你收到的許多錯誤*與自定義刪除無關。當然,包括你問題中的實際錯誤信息(應該總是這樣做)會證實這一點。 – WhozCraig
@WhozCraig我在代碼中添加了錯誤消息。 –
您無法使用此語法在班級中初始化成員。嘗試使用大括號或相等的初始值設定項。 –