Andy Guo
Andy Guo

Reputation: 127

customize std::shared_ptr deleter

In C++ Primer 5th, I've seen something like this:

shared_ptr<T> p(p2,d) p is a copy of the shared_ptr p2 except that p uses that p uses the callable object d in place of delete

But when I test it:

#include <memory>
#include <iostream>

class DebugDelete {
public:
    DebugDelete(std::ostream &o = std::cerr) : os(o) {}
    template <typename T> void operator()(T *p) const
    {
        os << "delete unique_ptr" << std::endl;
        delete p;
    }
private:
    std::ostream &os;
};

int main()
{
    std::shared_ptr<int> sptr, sptr1(sptr, DebugDelete());
}

what I quote seems wrong, sptr1(sptr, DebugDelete()) doesn't work, but sptr1(new int(42), DebugDelete()) works well.

So is it allowed to use a shared_ptr and a deleter to construct a share_ptr like in C++ Primer 5th? Thanks.

Upvotes: 1

Views: 3067

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36513

Look at shared_ptr constructors.

For the case where it does compile :

std::shared_ptr<int> sptr, sptr1(new int(42), DebugDelete());

It uses the fourth constructor noted:

template< class Y, class Deleter > shared_ptr( Y* ptr, Deleter d ); (4)

For the other case you mention :

std::shared_ptr<int> sptr, sptr1(sptr, DebugDelete());

It can't use this constructor because you're not passing a pointer, you're passing a different shared_ptr object.

Going down the list further, none of the constructors match the arguments here and thus you end up with a compilation error. That code is not standard-conformant which leads me to believe it's a tadbit different than what's in the book.

Upvotes: 2

Related Questions