What's the difference between shared pointers and normal ones?

According to the docs, shared pointers allow for many objects to own another object (I think?).

http://www.cplusplus.com/reference/memory/shared_ptr/

And the object is collected when all the shared pointers are gone.

But this sounds like normal pointers... what's the difference?
The difference is that you have to manually decide when to delete or delete[] a normal pointer - smart pointers do it for you using reference counting.
Oh.. what if I make a shared pointer that points to an object instantiated within a function and return the pointer?

This object would be stored on the stack for a normal pointer. Would a shared pointer store this object on the heap? Or would the shared pointer just go away because it detected the object on the stack just got erased when the function returned?
johnhoffman wrote:
Oh.. what if I make a shared pointer that points to an object instantiated within a function and return the pointer?
1. You can't take the address of an object returned by value, and 2. if you used some hack and got the address of a stack allocated object and it goes out of scope, that smart pointer doesn't keep it alive. Smart pointers are written in C++ just like your code is, they're not magical.
johnhoffman wrote:
This object would be stored on the stack for a normal pointer. Would a shared pointer store this object on the heap? Or would the shared pointer just go away because it detected the object on the stack just got erased when the function returned?
The smart pointer is not magic. it doesn't detect stack vs hap, doesn't automatically put stuff on the heap, doesn't "go away", and doesn't detect if the object got erased without it knowing.

Smart pointers are just instances of a class. The idea is that they themselves exist in the stack and can be copy constructed (passed by value, etc) and that once no more are referring to the same pointer, they call the deallocator you specified and delete the object you passed to them with new.

Like anything, you have to use them correctly, they just make it harder to mess up managing pointers yourself.
Topic archived. No new replies allowed.