They are all pointing to the same object? |
Not "all". You can have pointers to one object and other pointers to different object.
I don't understand when this would be used. |
1 2 3 4 5 6 7 8
|
void foo( int * bar ) {
}
int main( int argc, char ** argv ) {
int XX = 42;
int * gaz = &XX;
foo( gaz );
}
|
These are not smart pointers, nor point to dynamically allocated memory, but they show a "two to same" situation. The bar is a copy of gaz. Thus they both point to same object: XX. Making copies is very common. The argv points to different object(s) than gaz and bar.
When all the pointers are no longer pointing to an object the pointers are destroyed. |
Almost, but not quite (and the devil of programming is in the details).
When the last shared_ptr that points to specific dynamically allocated object Z ceases to point to Z,
the Z is destroyed.
The most common case, where shared_ptr ceases to point, is destruction of the pointer; the destructor of the pointer can delete the pointed to object.
That is not the only case. For example, the shared_ptr has member reset(). That can delete the pointed to object, but the pointer is a separate object that continues to exist.
In the above example the pointer bar exists only for the duration of the function call. The pointers gaz and argv live longer; to the end of main().
If the gaz and bar were std::unique_ptr's, the ownership would transfer form gaz to bar and gaz would no longer "own" pointed to object when foo() starts. The bar would delete the object at the end of foo().
If they were shared_ptr's, they would co-own (share) object for the duration of foo(), and gaz would do the deletion at the end of main().