Reputation: 9240
I have a shared pointer that I have shared around the system. Later on, I want to replace the actual content of these shared pointers point to, but still keep all the shared pointers valid, so they internally point to this new object.
Is there an easy way to do this with shared pointers?
Kind of like this I am looking for - pseudo-code
typedef boost::shared_ptr<Model> ModelPtr
ModelPtr model1 = ModelPtr(new Model);
ModelPtr model2 = model1;
// make something like 'model1.get() = new Model' so model1, model2 both points to a new model
EDIT: I want the effect of this, but less gimicky
ModelPtr model1 = ModelPtr(new Model("monkey"));
memcpy(model1 .get(), new Model("donkey"), sizeof(Model));
Upvotes: 16
Views: 18177
Reputation: 4695
shared_ptr<char> p(new char[256],std::default_delete<char[]>());
p.get()[0]='a';
memcpy do the job roughly.
You may try to use reset
method, but only affect the caller object.
Upvotes: 1
Reputation: 96241
Each shared_ptr
instance has its own copy of the pointer, so there's no way for any one shared_ptr
instance to know and affect the pointers of the other reference-counted shared_ptr
instances.
Do you instead just want model2
to be a reference to model1
so that when you reset model1
, model2 comes along with the change?
Otherwise can you elaborate further on the real problem you're trying to solve?
Upvotes: 1
Reputation: 33671
If I understood you correctly - you could use overloaded dereference operator:
auto a = std::make_shared<int>(42);
auto b = a;
*a = 43;
std::cout << *b << std::endl;
Output:
43
Upvotes: 14