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

3

8

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?

Internuncio answered 5/12, 2011 at 12:31 Comment(2)
possible duplicate of What C++ Smart Pointer Implementations are available?Volvox
Another, a better one : smart pointers explainedVolvox
S
18

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.

Springwood answered 5/12, 2011 at 12:38 Comment(0)
I
2

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.

Inveracity answered 5/12, 2011 at 12:39 Comment(0)
S
1

There can be many forms of smart pointers. Boost inspired shared_ptr which is now in C++11 is one of them. I suggest using shared_ptr at almost all the places when in doubt instead of auto_ptr which has many quirks.

In short, shared_ptr is just a reference counting implementation to share same object.

Refer: http://www.gotw.ca/publications/using_auto_ptr_effectively.htm http://en.cppreference.com/w/cpp/memory/shared_ptr

Sarracenia answered 5/12, 2011 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.