在shared_ptr中使用自定义的deleter

to use self-defined deleter in shared_ptr

本文关键字:自定义 deleter shared ptr      更新时间:2023-10-16

我定义了一个具有成员模板的类

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来初始化另一个。