What is the difference between auto pointers and shared pointers in C++

shreyasva picture shreyasva · Dec 5, 2011 · Viewed 10.4k times · Source

I have heard that auto pointers own their object whereas shared pointers can have many objects pointing to them. Why dont we use shared pointers all the time.

In relation to this what are smart pointers, people use this term interchangeably with shared pointers. Are they the same?

Answer

Cat Plus Plus picture Cat Plus Plus · Dec 5, 2011

std::auto_ptr is an outdated, deprecated implementation of exclusive pointer ownership. It's been replaced by std::unique_ptr in C++11. Exclusive ownership means that the pointer is owned by something, and the lifetime of the object is tied to the lifetime of the owner.

Shared pointers (std::shared_ptr) implement shared pointer ownership — they keep the object alive as long as there are alive references to it, because there is no single owner. It's usually done with reference counting, which means they have additional runtime overhead as opposed to unique pointers. Also reasoning about shared ownership is more difficult than reasoning about exclusive ownership — the point of destruction becomes less deterministic.

Smart pointer is a term that encompasses all types that behave like pointers, but with added (smart) semantics, as opposed to raw T*. Both unique_ptr and shared_ptr are smart pointers.