Is there a way to change the delete action on an existing instance of shared_ptr

Not really - the standard for shared_ptr is written in such a way that the Deleter may be stored by value in control node (a special object that contains the reference counter, holds deleter, tracks weak pointers etc). The deleter is type-erased, but if you know the concrete deleter type somehow, you can use std::get_deleter<Deleter, T>(t). With it you may access the deleter and change its state. Example:

struct A {};

struct deleter {
    void operator()(A* a) {delete a; }
    int m_state;
};

std::shared_ptr<A> ptr(new A(), deleter{});

std::get_deleter<deleter>(ptr)->m_state = 5;

And if you use just a function pointer for all deleters, then yes you can completely replace it, as all potential deleters use the same signature.

(Yes I know the question is 9 years old, but I've just faced this problem in 2020 and solved it like this. The possible reason for it is wrapping C pointers and objects from legacy code that manage ownership through raw pointers)


I don't think you can change the deleter once the shared_ptr was created.

But why would you do that ? Usually, when you create an object, you know immediatly how it must be destroyed. This is not likely to change.

If you really must do some specific treatments, you still can provide a custom deleter which does special things depending on the required logic.

Tags:

C++