C++11 Smart pointer

Source: Internet
Author: User

If you use new in your program to allocate memory from the heap (free storage), you should use Delete to release it when it is not needed. C + + introduces smart pointer auto_ptr to help automate this process. C++11 abandoned the auto_ptr and added three smart pointers: Unique_ptr, shared_ptr, weak_ptr.


I. auto_ptr, UNIQUE_PTR, shared_ptr

Header files: #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"));p s->comment ();} {shared_ptr<report> PS (new report ("Using shared_ptr"));p s->comment ();} {unique_ptr<report> PS (new report ("Using Unique_ptr"));p s->comment ();} return 0;}

Operation Result:


All pointer-only classes have a explict constructor that takes the pointer as a parameter, so you do not need to automatically convert the pointer to a smart pointer object.

Shared_ptr<double> p;

double* q = new double;

p = q; Not allowed, implicit conversion

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


Smart pointers, like regular pointers, can also perform dereference operations (*P), Access struct members (P-, m_), and assign them to regular pointers 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 actions:

String str ("hehe");

Shared_ptr<string> A (&STR); No!

When PTR expires, the program will use the delete operator for non-heap memory, which is an error.


Two.

For pointers to memory allocated on the heap, assigning values between pointers is unacceptable because the program will attempt to delete the same object two times.

There are several ways to avoid this problem:

1. Define the assignment operator so that it performs a deep copy. So two pointers will point to different objects, one of which is a copy of the other.

2. Establish the concept of ownership, for a particular object, only one smart pointer can have him, so that only the constructor that owns the smart pointer to the object will delete the object. Then, let the assignment action transfer ownership. This is for

Auto_ptr and Unique_ptr strategies, but Unique_ptr's strategy is more stringent.

3. Create a smarter pointer that tracks the number of smart pointers that reference a particular object. This is called a reference count. For example, when assigning a value, the count is 1, the pointer expires, the count is minus 1, and the delete is called only when the last pointer expires. This is the strategy adopted by shared_ptr.


auto_ptr<string> P1 (New string ("Auto");

auto_ptr<string> P2;

P2 = p1; Ok

After P2 takes over ownership of P1, P1 's ownership will be stripped. This prevents P1 and P2 destructors from attempting to delete the same object. But if you subsequently try to use P1, it would be a bad thing, because P1 is not pointing to valid data.


But if you replace the above auto_ptr with Unique_ptr, the compiler will consider P2 = p1, which is illegal, avoiding the problem of P1 not pointing to valid data, because UNIQUE_PTR is more secure than auto_ptr.


weak_ptr is a smart pointer introduced to fit shared_ptr to assist with shared_ptr work, which can be constructed from one shared_ptr or another Weak_ptr object, and its construction and destruction will not cause an increase or decrease in reference count. No overloads * and--but you can use lock to get an available shared_ptr objectan important use of weak_ptr is to obtain the shared_ptr of this pointer through lock, so that the object can produce shared_ptr to manage itself, but the helper class Enable_shared_from_this Shared_from _this will return the shared_ptr of this, just let the class you want to be managed by shared_ptr inherit from it.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C++11 Smart pointer

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.