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

I heard that auto pointers own their object, while shared pointers can have many objects pointing to them. Why don't we use shared pointers all the time.

In this regard, what are smart pointers, people use this term interchangeably with common pointers. They are the same?

+8
c ++ smart-pointers shared-ptr auto-ptr
source share
3 answers

std::auto_ptr - deprecated, deprecated implementation of exclusive right to a pointer. It has been replaced by std::unique_ptr in C ++ 11. Exclusive ownership means that the pointer belongs to something, and the lifetime of the object is tied to the lifetime of the owner.

Shared pointers ( std::shared_ptr ) implement pointer sharing - they keep the object alive as long as there are live links to it, because there are no owners. This is usually done with reference counting, which means they have extra run-time overhead rather than unique pointers. Also, the discussion of joint ownership is more complicated than the discussion of exclusive ownership - the point of destruction becomes less deterministic.

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

+18
source share

Generic pointers are a bit expensive as they contain a reference count. In some cases, if you have a complex structure with a common pointer at several recursive levels, one change may affect the number of links to many of these pointers.

Also, in several major processor architectures, atomic updating of the reference count may at least cost a little, but it is actually very expensive if several cores are currently accessing the same memory area.

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

Smart pointers are usually often used as a synonym for a common pointer, but actually cover the entire implementation of various pointers in boost, including one that looks like shared pointers.

+2
source share

There can be many forms of smart pointers. Boost inspared shared_ptr, which is now in C ++ 11, is one of them. I suggest using shared_ptr in almost all places where doubts arise, rather than auto_ptr, which has a lot of quirks.

In short, shared_ptr is just an implementation of reference counting for sharing the same object.

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

+1
source share

All Articles