C++11 Smart pointer

Source: Internet
Author: User

C into also pointer, defeat also pointer. Indeed, pointers provide a lot of convenience and flexibility to programmers, but improper use of pointers can cause a lot of problems.
Java and C # avoid pointers (though pointers can be used in C #, but few are expected to), and their garbage collection mechanism relieves programmers of the burden of managing memory.

In order to bring the pointer to a better experience, the concept of smart pointers is introduced in C + +, which essentially encapsulates some of the pointers ' operations into classes, and the programmer accesses the encapsulated pointer by using the familiar pointer operator (and *), which returns the encapsulated raw pointer through operator overloading.
C + + Smart pointers are similar to the process of creating objects in languages such as C #: After creating an object, it is the responsibility of the system to delete it at the correct time. The difference is that there is no separate garbage collector running in the background in C + +.
C + + Smart pointers are defined in the Std namespace in the <memory> header file.

There are two main types of smart pointers in C++11:
(1) shared_ptr represents a pointer to shared ownership (GKFX ownership). Multiple smart pointers can point to the same object, and when the last pointer to the object is destroyed, the object is automatically destroyed, freeing up space. Some of the other classes related to shared_ptr include: Weak_ptr,bad_weak_ptr,enable_shared_from_this and so on. SHARED_PTR is a smart pointer with a reference count, which releases the space that points to the object when the number of references is 0. SHARED_PTR effectively control the generation of the hanging hands (dangling points).

(2) unique_ptr represents a pointer to "exclusive ownership" (exclusive ownership). For an object, the pointer ensures that only one smart pointer points to the object at any time. Of course, you can transfer ownership, let the pointer release a reference to the object, and let the other pointer point to the object. Unique_ptr effectively prevent memory leaks (resource leaks).

See below for an example to further understand:
Here is an example of a shared_ptr use (the following is an excerpt from the book "the C + + standard Library")

//Util/sharedptr1.cpp#include <iostream>#include <string>#include <vector>#include <memory>using namespace STD;intMain () {//both shared pointers representing and persons by their name    shared_ptr<string> Pnico (New string("Nico"));shared_ptr<string> Pjutta (New string("Jutta"));//Capitalize person names(*pnico) [0] = ' N '; Pjutta->replace (0,1,"J");//Put them multiple times in a container     vector<shared_ptr<string>> Whomadecoffee;    Whomadecoffee.push_back (Pjutta);    Whomadecoffee.push_back (Pjutta);    Whomadecoffee.push_back (Pnico);    Whomadecoffee.push_back (Pjutta); Whomadecoffee.push_back (Pnico);//Print all elements     for(AutoPtr:whomadecoffee) {cout<< *ptr <<" "; }cout<< Endl;//Overwrite a name again*pnico ="Nicolai";//Print all elements again     for(AutoPtr:whomadecoffee) {cout<< *ptr <<" "; }cout<< Endl;//Print some internal data    cout<<"Use_count:"<< whomadecoffee[0].use_count () << Endl;}

Output Result:

Why is the last reference to the Whomadecoffee[0] object 4? The first one is the Pjutta pointer itself, which counts as a reference, then there are three copies: Whomadecoffee[0], whomadecoffee[1], whomadecoffee[3], so altogether it adds up to 4.

The above foreach statement can be replaced with the following for loop if it does not perform properly. foreach is a new feature of C++11, which seems to be unsupported in visual Studio2010, but is supported in 2013:

// print all elementsfor (vector<shared_ptr<string>>::iterator iter = whoMadeCoffee.begin(); iter != whoMadeCoffee.end(); ++iter){    cout" ";}cout << endl;

The following are examples of use of unique_ptr:

intMain () {//Create a unique_ptr pointer and initialize it. Because the Unique_ptr constructor is declared as explicit, it cannot be initialized in such a way that unique_ptr<string> pStr = new String ("Hello"). unique_ptr<string> PStr (New string("Hello"));//Output pointer pstr The object content pointed to    cout<< *pstr <<' \ n ';//Modify the object content pointed to by the pointer pstr*pstr ="Hello";///output pointer pstr The object content pointed to again    cout<< *pstr <<' \ n ';the//release function releases the pointer pstr and assigns the location of the object pointed to by the pointer to Potherstr    string* Potherstr = Pstr.release ();//This time the pstr pointer is definitely nullptr, and the output pointer potherstr to the object's contents    if(PStr = =nullptr)    {cout<< *potherstr <<' \ n '; }//Smart pointer pstr cannot use DELETE to free up space, but normal pointer potherstr uses delete for space release after use    DeletePOTHERSTR;return 0;}

Operation Result:

Smart pointers are similar to normal pointers, but it is important to remember that smart pointers cannot use the DELETE keyword to display free space. But we can customize what we do when we free up space in the smart pointer's constructor.

Finally, some people may also encounter auto_ptr such a pointer, auto_ptr is C++98 Standard, is now declared obsolete, unique_ptr can completely replace auto_ptr, so do not use auto_ptr in the future.

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.