Search code examples
c++shared-ptr

Replace all references to a object in a shared_ptr<T>


Is it possible to replace the object where multiple instances of a shared_ptr refer to? Maybe I am not really clear, so I'll give an example:

shared_ptr<Base> a = new Derived1();
auto b = a;
auto c = b;

// This function replaces the object where a, b, and c point to.
magic(a, new Derived2());

I have looked into the member functions of shared_ptr (reset and swap) with no luck.


Solution

  • Add an additional layer of indirection:

    shared_ptr<unique_ptr<Base>> a = unique_ptr<Base>(new Derived1());
    auto b = a;
    auto c = b;
    
    // This modifies the `unique_ptr` that `a` `b` and `c` point to
    // to point to a new Derived2.
    *a = unique_ptr<Base>(new Derived2());