C++11 Smart pointers for new features (SHARED_PTR/UNIQUE_PTR/WEAK_PTR)

Source: Internet
Author: User
shared_ptr Basic Usage

SHARED_PTR uses reference counting to manage the objects that are pointed to. When a new shared_ptr points to the same object (copy shared_ptr, etc.), the reference count is added to 1. The reference count is reduced by 1 when shared_ptr leaves the scope. When the reference count is 0 o'clock, the managed memory is freed.

The advantage of this is that it frees up the programmer's pressure to manually release memory. Before, in order to deal with exceptions in the program, it is often necessary to manually encapsulate the pointer into the class, through the destructor to release the dynamically allocated memory; Now this process can be handed over to shared_ptr.

Generally we use make_shared to get shared_ptr.

cout<< "Test shared_ptr base usage:" <<endl;shared_ptr<string> p1 = make_shared<string> (""); if (P1 && P1->empty ()) *p1 = "Hello"; Auto P2 = make_shared<string> ("World");cout<<*p1<< ' <<*p2<<endl; cout<< "Test shared_ptr use_count:" <<endl;cout<< "P1 cnt:" <<p1.use_count () << "\TP2 CNT: "<<p2.use_count () <<endl; Auto P3 = p2;cout<< "P1 cnt:" <<p1.use_count () << "\TP2 cnt:" <<p2.use_count () << "\TP3 cnt:" <<p3.use_count () <<endl;p2 = p1;cout<< "P1 cnt:" <<p1.use_count () << "\TP2 cnt:" << P2.use_count () << "\TP3 cnt:" <<p3.use_count () <<endl;

shared_ptr and New

Shared_ptr can be initialized with a pointer returned by a new expression.

cout<< "Test shared_ptr and New:" <<endl;shared_ptr<int> P4 (new int (1024x768));//shared_ptr<int> P5 = new int (1024); Wrong, no implicit constructorcout<<*p4<<endl;

However, a pointer returned by a new expression cannot be assigned a value to shared_ptr.

In addition, it is important to note that do not mix new and shared_ptr!

void process (shared_ptr<int> ptr) {cout<< "in Process Use_count:" <<ptr.use_count () <<endl;} cout<< "Don t mix shared_ptr and Normal pointer:" <<endl;shared_ptr<int> P5 (new int (1024x768));p rocess (P5 ); int v5 = *p5;cout<< "V5:" <<v5<<endl; int *P6 = new int (1024x768);p rocess (shared_ptr<int> (P6)); int v6 = *p6;cout<< "V6:" <<v6<<endl;

The above program fragment will output:

In Process Use_count:2
v5:1024
In Process Use_count:1
v6:0
As you can see, when the second process P6, the reference count for shared_ptr is 1, and when you leave the scope of the process, the corresponding memory is released, and P6 becomes the hanging pointer.

So, once the pointer returned by a new expression is managed by shared_ptr, stop accessing the memory with a normal pointer!

Shared_ptr.reset

The shared_ptr can be reset to another object through the Reset method, at which point the reference count of the original object is reduced by one.

cout<< "Test shared_ptr Reset:" <<endl;cout<< "P1 cnt:" <<p1.use_count () << "\TP2 cnt:" <<p2.use_count () << "\TP3 nt:" <<p3.use_count () <<endl;p1.reset (New string ("Cpp11")); cout << "P1 cnt:" <<p1.use_count () << "\TP2 cnt:" <<p2.use_count () << "\TP3 cnt:" <<p3.use _count () <<endl;shared_ptr deleter

You can customize a deleter function that is called when shared_ptr releases an object.

void Print_at_delete (int *p) {cout<< "Deleting ..." <<p<< ' \ t ' <<*p<<endl;delete p;} cout << "Test shared_ptr deleter:" <<endl;int *p7 = new int (1024x768);shared_ptr<int> P8 (P7, print_at_delete); P8 = make_shared<int> (1025);

UNIQUE_PTR Basic Usage

Unique_ptr is exclusive to the object to which it is pointing, as its name implies. Therefore, unique_ptr can not be copied, assigned to the operation, but can be transferred through the release function between Unique_ptr control.

cout<< "Test unique_ptr base usage:" <<endl;unique_ptr<int> up1 (new int (1024x768));cout<< "Up1:" <<*up1<<endl;unique_ptr<int> up2 (Up1.release ());cout<< "up2:" <<*up2<<endl;// Unique_ptr<int> Up3 (UP1); Wrong, unique_ptr can not copy//up2 = up1; Wrong, unique_ptr can not copyunique_ptr<int> up4 (new int (1025)); Up4.reset (Up2.release ());cout<< "UP4:" <<*up4<<endl;

Unique_ptr as parameters and return values

There are two special cases for the limitation of the copy, that is, unique_ptr can be used as the return value and parameter of the function, although there is also an implied copy exists, but it is not not.

unique_ptr<int> Clone (int p) {return unique_ptr<int> (new int (p))} void Process_unique_ptr (unique_ptr< Int> up) {cout<< "process unique ptr:" <<*UP<<ENDL;} cout<< "Test unique_ptr parameter and return value:" <<endl;auto up5 = Clone (1024x768);cout<< "UP5:" < <*up5<<endl;process_unique_ptr (Move (UP5));//cout<< "UP5 after process:" <<*up5<<endl; would cause Segmentfault

Here's the Std::move function, and then separately detailed ^_^

Unique_ptr deleter

Unique_ptr can also set deleter, unlike shared_ptr, which needs to specify the type of deleter in the template parameters. Fortunately we have decltype this sharp weapon, otherwise it is very troublesome to write.

cout<< "Test unique_ptr deleter:" <<endl;int *p9 = new int (1024x768); Unique_ptr<int, Decltype (print_at_ Delete) *> up6 (P9, Print_at_delete);unique_ptr<int> up7 (new int (1025)); Up6.reset (Up7.release ());

Weak_ptr

WEAK_PTR General and shared_ptr used together. It can point to the object that shared_ptr points to, but does not increase the object's reference count. This makes it possible to have a situation where the object that weak_ptr points to has actually been released. Therefore, WEAK_PTR has a lock function that attempts to retrieve a shared_ptr that points to an object.

cout<< "Test weak_ptr Basic usage:" <<endl;auto P10 = make_shared<int> (1024x768);weak_ptr<int> WP1 ( P10);cout<< "P10 use_count:" <<p10.use_count () <<endl;//p10.reset (new int (1025)); This would cause wp1.lock () return a false objshared_ptr<int> P11 = Wp1.lock (), if (p11) cout<< "WP1:" << *p11<< "Use Count:" <<p11.use_count () <<endl;

Summarize

SHARED_PTR uses reference counting to manage the objects that are pointed to.
Shared_ptr can be initialized with a pointer returned by a new expression, but a pointer returned by a new expression cannot be assigned to shared_ptr.
Once the pointer returned by a new expression is managed by shared_ptr, the memory is not accessed through a normal pointer.
The shared_ptr can be reset to another object through the Reset method, at which point the reference count of the original object is reduced by one.
You can customize a deleter function that is called when shared_ptr releases an object.
Unique_ptr is exclusive to the object to which it is pointing.
It is not possible to copy, assign, or manipulate unique_ptr, but you can transfer control between unique_ptr through the release function.
Unique_ptr can be used as a function's return value and as a parameter.
Unique_ptr can also set deleter, you need to specify the type of deleter in the template parameters.
WEAK_PTR General and shared_ptr used together. It can point to the object that shared_ptr points to, but does not increase the object's reference count.
WEAK_PTR has a lock function that attempts to retrieve a shared_ptr that points to an object.

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

Related Article

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.