[C ++] "C ++ 17 Introduction to the classic" study notes 11 ---- smart pointers: unique_ptr, shared_ptr, weak_ptr

Smart pointer template defines the memory type header files in the standard library, and will therefore have to include this file in your source file, you can use smart pointers.

std namespace defines three smart pointers:

1、unique_ptr<T>

unique_ptr <T> T points to an object similar to a pointer type, is unique, which means that there are not a plurality unique_ptr <T> object stored in the same address. In other words, there should never be two or more unique_ptr <T> objects simultaneously point to the same address.

unique_ptr <T> object is directed exclusively owned content. The compiler may not be copied by unique_ptr <T> to enforce this uniqueness.

2、shared_ptr<T>

shared_ptr <T> object is like a pointer pointing to T type, but unique_ptr <T> different, can have any number shared_ptr <T> object contains or share the same address. Thus, shared_ptr <T> object allows ownership of the shared objects on the free store.

At any given time, comprising a given number of known address shared_ptr <T> object runtime, called the reference count.

When the address contains shared_ptr <T> object is released or directed to another address; shared_ptr each time creating a new free store contains a given address <T> object, comprising the address shared_ptr <T> of the reference count is incremented the reference count is decremented.

When the address does not contain a given shared_ptr <T> object the reference count is 0, the object at that address space will be released. All point to the same address shared_ptr <T> object can access the reference count.

3、weak_ptr<T>

weak_ptr <T> is linked to share_ptr <T>, the address comprising the same. Creating weak_ptr <T> is not incremented linked shared_ptr <T> object's reference count, it can not prevent it points to an object to be released. It cited last shared_ptr <T> object is released or reset to point to another address, even if the link weak_ptr <T> object still exists, which also releases the memory. Even if this happens, weak_ptr <T> it does not contain a pointer suspension, at least not unintentionally comprising programmer access pointer. The reason is that the programmer can not access address weak_ptr <T> package directly.

The compiler will force first create a shared_ptr from weak_ptr <T> <> object to refer to the same address.

If weak_ptr <T> referenced memory address is still valid, force the creation shared_ptr <T> will first ensure that the reference count is incremented again, and the pointer can be safely used again. However, if the memory has been released, created shared_ptr <T> will contain nullptr.

 

Recommendation: Use vector <T> container rather than unique_ptr <T []>, because this type of container is much more powerful than smart pointers, but also much more flexible.

 


 

Guess you like

Origin blog.csdn.net/kingkee/article/details/94214704