Detailed explanation of c ++ smart pointers
Dynamic Memory
Each program has a memory pool called heap, which is used to store dynamically allocated objects, that is, objects allocated when the program is running. The life cycle of dynamic objects is controlled by the program. That is to say, when dynamic objects are no longer used, our code must display and destroy them.
It is necessary to use a sensible memory, but it is well known that correct management of dynamic memory is very tricky. For example, memory leakage occurs when you forget to release the memory. Sometimes there are pointer references pointing to the memory, but it is released, it will generate a wild pointer. Therefore, smart pointers are generated. C ++ 11 provides three types: shared_ptr, unique_ptr, and weak_ptr.
Shared_ptr
The technology used is the reference technology. The reference count is associated with a specific object. When shared_ptr pointing to this object increases, the reference count is automatically added, and the reference count is reduced. Release and modify an object when the referenced technology is 0. The reference count is automatically added when the value is assigned during initialization. Auto-subtraction occurs when the value is assigned and the structure is analyzed.
Shared_ptr <T> sp; empty smart pointer.
constexpr shared_ptr(nullptr_t) : shared_ptr() {}
Template <class U> explicit shared_ptr (U * p) does not support implicit conversion.
template <class U> shared_ptr (const shared_ptr<U>& x) noexcept;
template <class U> shared_ptr (shared_ptr<U>&& x) noexcept;
template <class U> shared_ptr& operator= (const shared_ptr<U>& x) noexcept;
template <class U> shared_ptr& operator= (shared_ptr<U>&& x) noexcept;
P is determined by p as a condition. If p points to an object, it is true.
* P calls p to obtain the object it points
P-> men is equivalent to (* p). men
P. get () returns the pointer saved in p.
Swap (p, q) swap pointer in p, q
P. swap (q)
Make_shared <T> (args) returns a shared_ptr pointing to an object of the dynamically allocated type T, which is initialized with args.
Shared_ptr <T> p (q)
P = q
P. unique () If p. use_count () is 1, true is returned; otherwise, false is returned.
P. use_count () returns the number of smart pointers to the p shared object for debugging.