Search code examples
c++templatesshared-ptr

to use self-defined deleter in shared_ptr


I define a class, which has a member template, in place of default deleter of 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;
};

When I apply it to the following code, some errors were reported:

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;
};

Solution

  • In initialize_list you can used self-defined deleter like

    shared_ptr<set<int>> r = shared_ptr<set<int>>(new set<int>, DebugDelete());
    

    and you should not use one shared_ptr to initialize another one.