Reputation: 253
If I have an object pointed-to by several pointers in several classes, and I decide at some point to "change" this object, is there a smart way to make all pointers pointing to that object point to the new object ? for example
class myClass{
//myCLass definition
}
void main(){
shared_ptr<myClass> ptr1, ptr2;
ptr1.reset(new myClass(1));
ptr2 = ptr1;
//Now two pointers pointing at object 1
shared_ptr<myClass> ptr3;
ptr3.reset(new myClass(2)); //new object created
ptr1 = ptr3; //make ptr1 point to object 2
//is there a smart way to make ptr2 also points at object 2?
}
Thanks
Upvotes: 3
Views: 157
Reputation: 15334
You are not actually "changing" the object. If you actually change the value of the object you wouldn't have this problem. You could either copy:
*ptr1 = *ptr3;
Or move:
*ptr1 = std::move(*ptr3);
Upvotes: 1
Reputation: 53155
As Brian pointed out in the comment, the easiest solution is to make ptr2 be a reference to ptr1. That way, once you change ptr1 (or ptr2 for that matter), they will be alright.
shared_ptr<myClass> ptr1;
shared_ptr<myClass> &ptr2 = ptr1;
Then, you will also be able delete the needless copy like this:
ptr2 = ptr1;
You could also write this as the operator=
returns a reference to the shared pointer, but I am not sure this is the smart solution you need:
ptr1 = ptr2 = ptr3;
Yet another mechanism would be to create your own function managing all this, and call that instead of the assignment operator, so something like a "smart setter".
Upvotes: 2