Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

shared-ptr

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.

like image 962
Tim Avatar asked Dec 30 '25 18:12

Tim


1 Answers

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());
like image 87
Mankarse Avatar answered Jan 01 '26 11:01

Mankarse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!