C ++ 11 smart pointer tutorial

Source: Internet
Author: User

If you use new in a program to allocate memory from the heap (free storage zone), you should use delete to release it when it is not needed. C ++ introduces the intelligent pointer auto_ptr to help automatically complete this process. C ++ 11 abandons auto_ptr and adds three smart pointers: unique_ptr, shared_ptr, and weak_ptr.

I. auto_ptr, unique_ptr, shared_ptr

Header file: # include <memory>

Usage:
Auto_ptr <double> A (new double );
Unique_ptr <int> B (new int );
Shared_ptr <string> C (new string>;

# Include <iostream> # include <memory> # include <string> using namespace std; class Report {public: Report (const string s): str (s) {cout <"Object create! \ N ";}~ Report () {cout <"Object deleted! \ N ";}void comment () const {cout <str <endl ;}private: string str ;}; int main () {auto_ptr <Report> ps (new Report ("using auto_ptr"); ps-> comment ();} {shared_ptr <Report> ps (new Report ("using shared_ptr"); ps-> comment ();} {unique_ptr <Report> ps (new Report ("using unique_ptr"); ps-> comment ();} return 0 ;}



Running result:



All pointer classes can have only one explicit constructor. This constructor can use pointers as parameters, so you do not need to automatically convert pointers to smart pointer objects.

Shared_ptr <double> p;

Double * q = new double;

P = q; // not allowed, implicit conversion

Pd = shared_ptr <double> (q); // OK, explict conversion


A smart pointer is similar to a regular pointer. It can also perform the unreferencing operation (* p), access the structure Member (p-> m _), and assign it to a regular pointer of the same type. You can also assign a smart pointer object to another smart pointer object of the same type.


Smart pointers should avoid the following operations:

String str ("hehe ");

Shared_ptr <string> A (& str); // NO!

When the ptr expires, the program will use the delete operator for non-heap memory, which is incorrect.


II.

For pointers pointing to heap-allocated memory, the assignment between pointers is unacceptable because the program will try to delete the same object twice.

To avoid this problem, there are multiple methods:

1. Define the value assignment operator to perform deep replication. In this way, the two pointers point to different objects, one of which is another copy.

2. Establish the concept of ownership. For a specific object, only one smart pointer can own it. In this way, only constructors with smart pointers will delete the object. Then, let the assignment operation transfer ownership. This is used

Auto_ptr and unique_ptr, but the unique_ptr policy is stricter.

3. Create smart and higher pointers to track the number of smart pointers that reference specific objects. This is called reference count. For example, when a value is assigned, the value of Count plus 1, and when the pointer expires, the value of count minus 1. delete is called only when the last pointer expires. This is the shared_ptr policy.


Auto_ptr <string> p1 (new string ("auto ");

Auto_ptr <string> p2;

P2 = p1; // OK

After p2 takes over the p1 ownership, the p1 ownership will be denied. This prevents the destructor p1 and p2 from trying to delete the same object. However, if you try to use p1 later, this will be a bad thing because p1 does not point to valid data.


However, if you replace auto_ptr with unique_ptr, the compiler considers p2 = p1; this statement is invalid. This avoids p1 from pointing to valid data because unique_ptr is safer than auto_ptr.

Weak_ptr is a smart pointer introduced to assist shared_ptr in combination with shared_ptr. It can be constructed from one shared_ptr or another weak_ptr object, its Construction and Analysis structure will not increase or decrease the number of reference records. No overload * and->, but you can use lock to obtain an available shared_ptr object.
An important purpose of weak_ptr is to obtain the shared_ptr of this pointer through lock so that the object can manage itself by producing shared_ptr, but shared_from_this of the helper class enable_shared_from_this will return shared_ptr of this, you only need to inherit the class managed by shared_ptr.



C ++ 11 can use smart pointers

A smart pointer is a class (Template) implemented based on the RAII mechanism. It has pointer behavior (with operator * and operator-> operators reloaded) and can "intelligently" destroy the objects it refers. In C ++ 11, intelligent pointers such as unique_ptr, shared_ptr, and weak_ptr can be used to manage dynamic resources.

That is, smart pointers with reference count and memory can be automatically released include the following:
Unique_ptr: If the ownership of memory resources does not need to be shared, you should use this (it does not copy the constructor), but it can be transferred to another unique_ptr (there is a move constructor ).
Shared_ptr: if the memory resources need to be shared, use this (so this name is called ).
Weak_ptr: holds the reference of the object managed by shared_ptr, but does not change the reference count value. It is used to break the dependency loop (imagine that in a tree structure, the parent node references the child node through a shared ownership reference (chared_ptr), and the child node must hold the reference of the parent node. If the second reference also shares ownership, it will lead to a loop, and the memory of both nodes will not be released ).
It is worth noting that auto_ptr has been discarded and will not be used any more.

1. unique_ptr smart pointer usage

// Create a smart pointer std: unique_ptr <MyClass> mc (new MyClass); mc. reset (new MyClass); // "bind" dynamic object; and release the previously "bound" object. Std: unique_ptr <MyClass> mmc (new MyClass); mmc = std: move (mc); // The original "bound" object of mmc, released, mmc re-binds the "bound" object "to mc and changes it to a null smart pointer. mmc = nullptr; // explicitly destroys the indicated object and changes the smart pointer to a null pointer. Equivalent to u_s2.reset () mc. reset (new MyClass); // "bind" dynamic object; if (mmc = nullptr) {mmc = std: move (mc );}


2. Use cases of unique_ptr

(1) exception security guarantee for dynamic resources (using RAII features ):
Void foo ()
{// Abnormal security code. No matter whether an exception occurs or not, as long as the px pointer is successfully created, its destructor will be called to ensure that dynamic resources are released.
Unique_ptr <X> px (new X );
// Do something to automatically release resources.
}
(2) return the dynamic resources created in the function.
Unique_ptr <X> foo ()
{  
Unique_ptr <X> px (new X );
// Do something
Return px; // mobile semantics
}
Std: unique_ptr <MyClass> mmcn = foo ();

(3) can be placed in the container (to make up for the disadvantage that auto_ptr cannot be a container element)
Method 1:
Vector <unique_ptr <string> vs {new string {"Doug"}, new string {"Adams "}};
Method 2:
Vector <unique_ptr <string> v;
Unique_ptr <string> p1 (new string ("abc "));
V. push_back (std: move (p1); // The explicit moving semantics is required here, because unique_ptr does not have the copy semantics.
(4) manage dynamic arrays. Because unique_ptr has a unique_ptr <X []> overloaded version, delete [] is called when a dynamic object is destroyed.
Unique_ptr <int []> p (new int [3] {1, 2, 3 });
P [0] = 0; // operator [] is Reloaded

3. shared_ptr smart pointer usage

The shared_ptr method is a little more simple. {Std: shared_ptr <MyClass> myDevice; // create a smart pointer std: shared_ptr <MyClass> device = std: make_shared <MyClass> (); // create a smart pointer and point it to an object. The reference value is 1. if (! MyDevice. unique () {myDevice = device; // reference + 1; then 2.} // release the memory


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.