Tips for C ++ Primer Chapter 12 dynamic memory, primerchapter
Chapter 1 different memory management modes of dynamic memory
Static Memory: stores local static objects, class static data members, and variables defined outside of any function.
Stack memory: non-static objects stored within the function.
Memory Pool | free space | heap: stores dynamically allocated objects.
PS: dynamic memory that is no longer in use must be explicitly destroyed
C ++ 11 provides smart pointers: shared_ptr allows multiple pointers to point to the same object; unique_ptr excludes the object; it also defines an adjoint class named weak_ptr, it is a weak reference that points to the objects managed by shared_ptr. (These three types are defined in the header file memory)
The smart pointer Automatically releases the specified object.
Operations supported by shared_ptr and unique_ptr
Shared_ptr <T> sp unique_ptr <T> up a null smart pointer that can point to an object of the T type.
P uses p as a condition judgment. If p points to any object, it is true.
* P is used to obtain the object referred to by p.
P-> mem is equivalent to (* p). mem
P. get () returns the pointer stored in p. Be cautious when using this function. If the smart pointer releases its object, the pointer returned by this method also becomes invalid.
Swap (p, q) p. swap (q) Exchange pointers in p and q
Exclusive shared_ptr operations
Make_shared <T> (ArgsReturns a shared_ptr <T>, pointing to a dynamically Assigned T-type object.ArgsInitialize this object. IfArgsIf it is null, the value is initialized.
Shared_ptr <T> p (q) p is a copy of q. This operation increments the counter in q. pointers in q must be converted to T *
P = q p and q are both shared_ptr, And the stored pointers must be converted to each other. This operation will decrease the reference count of p and increase the reference count of q; if the reference count of p is 0, the original memory managed by p is released.
P. use_count () returns the number of pointers to the shared object with p. It may be slow and is mainly used for debugging.
P. unique () If use_count is 1, true is returned; otherwise, false is returned.
Copy, assign value, and reference count of shared_ptr
Whenever a shared_ptr is copied, the counter increments. For example, when you use one shared_ptr to initialize another shared_ptr, pass it as a parameter to a function, or use it as the return value of the function, the associated counter will increase progressively;
When a shared_ptr is assigned a new value or the shared_ptr is destroyed (for example, when a local shared_ptr leaves its scope), the counter will decrease;
When the counter of shared_ptr changes to 0, it automatically releases the objects it manages.