Search code examples
c++shared-ptr

shared_ptr assignment - is custom deleter copied too?


Much of the documentation states that on assignment the managed object is copied. Nothing seems to talk about the deleter or the control block.

For example:

std::shared_ptr<A> a(new A, D());
std::shared_ptr<A> b;

b = a;

If b is the last remaining owner and b falls out of scope, will the custom deleter D() be called?


Solution

  • Yes. The deleter is set when the object is created. Shared pointers manage the reference count in the control structure that has the deleter.

    std::shared_ptr<A> a(new A, D());
    

    This line creates a new shared object with a control structure that contains a deleter and a reference count of one. It also creates a shared pointer to that object and control structure.

    std::shared_ptr<A> b;
    b = a;
    

    This creates a second reference to that object and control structure, bumping its reference count to two.

    The same structure that holds the one and only reference count for the shared object also contains the deleter.