在shared_ptr中使用自定义的deleter
to use self-defined deleter in 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;
};
在initialize_list中您可以使用自定义的deleter,例如
shared_ptr<set<int>> r = shared_ptr<set<int>>(new set<int>, DebugDelete());
,您不应使用一个共享_ptr来初始化另一个。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 带有自定义deleter的std::unique_ptr对象的大小(一个由ref捕获的lambda)
- primr 5版.自定义deleter函数的unique_ptr构造函数
- shared_ptr陌生性,带有零值和自定义deleter
- 使用自定义deleter类型定义std::shared_ptr的别名
- 在shared_ptr中使用自定义的deleter
- std::unique_ptr的自定义deleter是手动调用析构函数的有效位置吗
- 使用std::shared_ptr将成员函数用作自定义deleter时出现问题
- 如何编写一个可以接受函数指针和/或函子的类,就像智能指针对自定义deleter所做的那样
- 使用unique_ptr和自定义deleter时感到困惑
- 用自定义deleter封装C型指针的常见方法
- 带有自定义deleter和分配器的shared_ptr
- 如何为包装需要2个参数的c函数的unique_ptr类成员创建自定义deleter
- 使用带有uniqueptr的自定义deleter
- 正在为共享指针调用自定义deleter类成员函数
- 将带有自定义deleter的unique_ptr移动到shared_ptr
- 自定义deleter以通过std::unique_ptr解除分配2D阵列
- C++11使用带有自定义deleter的unique_ptr
- 带有自定义deleter的Unique_ptr构造函数被删除