Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 242
shreyasva Avatar asked Dec 05 '11 12:12

shreyasva


2 Answers

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.

like image 144
Cat Plus Plus Avatar answered Oct 06 '22 18:10

Cat Plus Plus


Shared pointers are slightly more costly as they hold a reference count. In some case, if you have a complex structure with shared pointer at multiple recursive levels, one change can touch the reference count of many of those pointers.

Also in multiple CPU core architectures, the atomic update of a reference count might become not slightly costly at least, but actually really costly, if the multiple core are currently accessing the same memory area.

However shared pointers are simple and safe to use, whereas the assignment properties of auto pointers is confusing, and can become really dangerous.

Smart pointers usually is frequently used just as a synonym of shared pointer, but actually covers all the various pointers implementation in boost, including the one that's similar to shared pointers.

like image 42
jmd Avatar answered Oct 06 '22 20:10

jmd