我定义了一个类,它有一个成员模板,代替了std :: 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;
};
答案 0 :(得分:0)
在initialize_list中,您可以使用自定义删除器,如
shared_ptr<set<int>> r = shared_ptr<set<int>>(new set<int>, DebugDelete());
并且您不应该使用一个shared_ptr来初始化另一个。