Reputation: 5681
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.
Upvotes: 3
Views: 1037
Reputation: 40603
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());
Upvotes: 4