A smart pointer (c++);
- shared_ptr,unique_ptr,weak_ptr,auto_ptr
- Four smart Pointers in C++ : auto_ptr, shared_ptr, weak_ptr, unique_ptr the last three are supported by C++ 11, and the first one has been abandoned by 11.
Why use smart Pointers:
- The purpose of smart Pointers is to manage a pointer because a memory leak occurs when requested space is forgotten at the end of the function. Using smart Pointers avoids this problem to a large extent, because smart Pointers are a class that, when out of scope, automatically calls a destructor that automatically frees resources. So the principle of the smart pointer is to automatically free the memory space at the end of the function, no need to manually free the memory space.
unique_ptr
- Unique_ptr implements the concept of exclusive or strict ownership, ensuring that only one smart pointer can point to the object at a time. It is particularly useful for avoiding resource leaks, such as “forgetting to call DELETE after creating an object with new because of an exception”
- The unique_ptr assignment conversion uses move Release reset as described below
Shared_ptr Shared_ptr implements the concept of shared ownership. Multiple smart Pointers can point to the same object, and the object and its associated resources are released when “the last reference is destroyed.” The name share indicates that a resource can be shared by multiple Pointers, which uses a counting mechanism to indicate that the resource is shared by several Pointers. You can view the number of owners of a resource using the member function use_count(). In addition to being constructed by new, it can also be constructed by passing in auto_ptr, unique_ptr, Weak_ptr. When we call release(), the current pointer releases resource ownership and the count is reduced by one. When the count equals zero, the resource is freed. Shared_ptr addresses the limitations of auto_ptr on object ownership (auto_ptr is exclusive) by providing a smart pointer to shared ownership using a reference counting mechanism. Member functions: Unique Returns exclusive ownership (use_count is 1) SWAP Exchanges two shared_ptr objects (use_count is 1) reset Relinquish ownership of an internal object or changes to an object. Get returns the internal object (pointer), which is the same as using the object directly, since the () method has been overridden. Such as from sp (new int (1)); Sp is equivalent to sp.get()