+ 2
Why there us a need to have multiple ownership of shared pointer pointing to one object?
As shared pointer can have multiple ownership of one object. So, if we update the value of any one of the member of object using one shared pointer it pointing to then that will effect in all other shared pointer which are pointing to same object or having ownership of it. Then what is the point in having multiple ownership/shared pointer of one object?What is the purpose of doing that? Can we also perform deep copy here to have seprate memory space allocated for each and every ownership?
1 Antwort
+ 2
Well, you mentioned copying, and as far as I know, that is exactly the point of shared pointers. A unique pointer manages its stored pointer exclusively, so copying it is forbidden. Instead, if you want to pass a unique pointer around, you are bound to moving it instead, so the original object is no longer valid after such an operation. On the opposite, a shared pointer doesn't necessarily needs to manage its pointer single-handedly, so you can pass it around in your application without having to worry about anything.
Note that no deep copy is performed when copying a shared pointer. Instead, both objects will store a pointer pointing to the same location, together with a counter keeping track of how many objects share the ownership of the pointer. Only the last object being destroyed will also delete the pointer.
So yeah, in conclusion, use unique pointers if you are fine with moving the pointer around, otherwise consider shared pointers.