【发布时间】:2016-12-18 10:00:54
【问题描述】:
我定义了一个类,它有一个成员模板,代替 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;
};
【问题讨论】:
-
我怀疑您收到的许多错误与自定义删除无关。当然,在您的问题中包含实际的错误消息(应该始终这样做)将证实这一点。
-
@WhozCraig 我已经在代码中添加了错误消息。
-
你不能用这种语法初始化一个类中的成员。尝试使用大括号或等号初始化程序。
-
@n.m.但是在成员函数中,我标记为 3 的行有效,就像我评论 Blue moe 的答案一样。
-
在成员函数中是一回事。不在成员函数中是另一回事。无论如何,总是使用大括号:
std::shared_ptr<std::set<int>> r{new std::set<int>, DebugDelete()};
标签: c++ templates shared-ptr