C++11 Smart pointer

Source: Internet
Author: User

To address the problem of C + + memory leaks, C++11 introduced smart pointers (smart Pointer).

The principle of smart pointers is to accept a well-applied memory address, construct a smart pointer object stored on the stack, there is an important principle in C + +, at the end of the function (whether it is normal return, or because of the exception division of the PvP fallback), all the stack objects will be destroyed, that will call all the Stack object's destructor. The memory stored inside the smart pointer is also freed (unless the smart pointer is saved).

C++11 provides three smart pointers: Std::shared_ptr, Std::unique_ptr, std::weak_ptr, add header file <memory> when used.

SHARED_PTR uses a reference count, and each copy of the shared_ptr points to the same memory. Every time he uses it, the internal reference count is added 1, each destructor is made, the internal reference count is reduced by 1, minus 0 o'clock, and the pointed heap memory is deleted. The reference count inside the shared_ptr is secure, but the read of the object needs to be locked.

1. shared_ptr1.1 Basic Usage

(1) initialization

You can initialize shared_ptr by constructors, std::make_shared<t> helper functions, and the Reset method

#include"stdio.h"#include<memory>#include<iostream>using namespacestd;voidMain () {shared_ptr<int> P1 (New int(Ten)); cout<<"reference count for P1:"<<p1.use_count () <<Endl; shared_ptr<int> p2 =P1; cout<<"reference count for P1:"<< P1.use_count () <<"reference count for P2:"<< P2.use_count () <<Endl; P2.reset (New int(2));//calling rest causes the reference count to be reduced by 1 when there is a value in the smart pointercout <<"reference count for P1:"<< P1.use_count () <<"reference count for P2:"<< P2.use_count () <<Endl; cout<< *P2 <<Endl;     P2.reset (); cout<<"reference count for P1:"<< P1.use_count () <<"reference count for P2:"<< P2.use_count () <<Endl; shared_ptr<int> P3 = make_shared<int> ( -); shared_ptr<int>P4; P4.reset (New int( -)); cout<<"reference count for P4:"<< P4.use_count () <<Endl;}

Note: You cannot assign a raw pointer directly to a smart pointer

std::shared_ptr<intnewint(1); // Error

Reset () consists of two operations. Calling reset () causes the reference count to be reduced by 1 when there is a value in the smart pointer. When reset (new xxx ()) is called, the smart pointer first generates a new object, and then the reference count of the object is reduced by 1 (if, of course, the reference count is 0 o'clock, the old object is refactored), The new object's pointer is then handed to the smart pointer for safekeeping.

(2) Get the original pointer

std::shared_ptr<int> P4 (new int (5)), int *pint = P4.get ();

(3) Specify the delete device

A smart pointer can specify a filter that automatically invokes the specified delete to free memory when the reference count of the smart pointer is 0 o'clock. One reason that std::shared_ptr can specify a delete is that its default delete does not support array objects, which is important to note.

template<classclass d>*p, D D)
void DELETEINTPTR (int *p) {     delete  p;      } shared_ptr<int> P (newint(1), deleteintptr);

When we use shared_ptr to manage dynamic arrays, we need to specify a delete because the default std::shared_ptr of the array object is not supported

shared_ptr<int> P (newint[ten], [] (int *p) {delete[] p;});

You can also use the SYD::d Efault_delete as the Default_delete, which is implemented by calling delete.

shared_ptr<int> P (newint[ten], deault_delete<int[]>);

(4) Note the use of Make_share and Make_arrar_share

(5) Precautions to use shared_ptr

A. Do not initialize multiple shared_ptr with a raw pointer initialization

B. Do not create shared_ptr in function arguments

2. Unique_ptr Exclusive Pointers

Unique_ptr is an exclusive smart pointer that does not allow other smart pointers to share its internal pointers, and does not allow assigning one unique_ptr to another unique_ptr,unique_ptr does not allow replication. However, it can be returned to other unique_ptr through a function, and it can be moved to other unique_ptr, so that it has ownership of the original pointer.

Note: Unique_ptr does not support Make_share

3. weak_ptr Weak reference pointer

The weak reference pointer week_ptr is used to monitor the shared_ptr, does not make the reference count plus 1, it does not manage pointers inside the shared_ptr, week_ptr no overloaded operators, does not share pointers, and does not manipulate resources. The weak_ptr pointer can be used to return the this pointer and solve the problem of circular references

(1) Use_count gets the reference count of the current observation resource

shared_ptr<int> P (newint(1)); weak_ptr<int>  << p1.use_count () <<endl;

(2) Determine whether the observed resource has been released by expired ()

(3) Use lock () to get the shared_ptr of the monitor

(4) weak_ptr returns the This pointer

You cannot directly return the this pointer to shared_ptr, you need to return a smart pointer by deriving the Std::enable_shared_from_this class, and by its method shared_from_this, because Enable_shared_ There is a weak_ptr pointer in the From_this class that is used to observe the This smart pointer, call Shared_from_this, and invoke the internal weak_ptr lock () method.

(5) Weak_ptr solve the problem of circular reference

#include"stdio.h"#include<memory>#include<iostream>using namespacestd;classB;classa{ Public: shared_ptr<B>bptr; ~A () {cout<<"A is delete!"<<Endl; }};classb{ Public: shared_ptr<A>aptr; ~B () {cout<<"B is delete!"<<Endl; }};voidMain () {{shared_ptr<A> A (NewA ()); shared_ptr<B> B (NewB ()); A->bptr =b; b->aptr =A; cout<<"reference count for a:"<< A.use_count () <<Endl; cout<<"reference count for B:"<< B.use_count () <<Endl; }    inti =0;}

The reference count minus 1 after leaving the scope does not remove the pointer, causing a memory leak

Solve this problem by weak_ptr, as long as you change any member of a or B to weak_ptr

C++11 Smart pointer

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.