Smart Pointer to c++11 __c++

Source: Internet
Author: User
Smart pointers to c++11Original link: To c++11 smart pointers, forwarding please indicate the source.
long-awaited begins.

The last article "from the Auto_ptr" in detail summed up the c++98 standard in the auto_ptr, but with the arrival of C++11, Auto_ptr is no longer, is about to become history; good things are always welcome, as everyone is using "quasi" Standard library boost shared_ptr;c++ Standards committee finally felt it was time to join shared_ptr to c++11. Cheers, at least I feel so, at least shared_ptr let me use it, or good. Next, summarize the smart pointers in the c++11. what smart pointers are c++11

Let's start with a simple piece of code to see what smart pointers are in the c++11.

/************************************************************************* > File Name:SmartPointDemo.cpp > author:jelly > Mail:vipygd#126.com (#->@) > Created time:2014 Year October 16 Thursday 15:25 43 seconds ***************************

/#include <iostream> #include <memory> using namespace std;  int main () {unique_ptr<int> up1 (new int (10));///Cannot copy unique_ptr//unique_ptr<int> up2 = up1;//

    This is wrong, cout<<*up1<<endl;. Unique_ptr<int> Up3 = Move (UP1);
    Now UP3 is the only unique_ptr smart pointer to the data cout<<*up3<<endl; cout<<*up1<<endl; Run-time error Up3.reset (); Show free Memory Up1.reset (); Even if Up1 does not have any memory, this call is no problem//cout<<*up3<<endl;
    The UP3 has been released, so it will run incorrectly shared_ptr<int> SP1 (new int (20)); Shared_ptr<int> SP2 = SP1;
    This is perfectly OK, add reference count cout<<*sp1<<endl;

    cout<<*sp2<<endl; Sp1.reset (); Reduce referencesCount cout<<*sp2<<endl;
return 0;
 }

The three smart pointers, Unique_ptr, shared_ptr, and weak_ptr, are mainly provided in c++11 to automatically recycle heap-allocated objects. Look at the code above, the feeling is also very easy to use, but also good, at least better than auto_ptr. unique_ptr

The unique_ptr in C++11 is a substitute for auto_ptr, which has the unique property of ownership as Auto_ptr, unlike Auto_ptr, where UNIQUE_PTR does not replicate constructors, which prevents some "quietly" A problem with lost ownership occurs, and you can do this if you need to transfer ownership:

Unique_ptr<int> Up3 = Move (UP1); The UP3 is now the only UNIQUE_PTR smart pointer

//or
unique_ptr<int> up4 (Move (Up1)) of the data.

The transfer of ownership occurs only after the call Std::move by the user shows, so that the user knows what he is doing. Another piece of code to see the use of unique_ptr as a function parameter and return value:

/*************************************************************************
> File Name:unique_ptrDemo.cpp
> Author:jelly
> Mail:vipygd#126.com (#->@)
> Created time:2014 Year October 16 Thursday 17:10 49 sec
* * * /

#include <iostream>
Include <memory>
using namespace std;

Unique_ptr<int> Func (unique_ptr<int> a)
{         
    cout<<*a<<endl;
    return A;
}         

int main ()
{         
    unique_ptr<int> up1 (new int);

    Up1 = Func (Move (Up1));
    cout<<*up1<<endl;

    return 0;
}

Because the constructor is not replicated in unique_ptr, therefore, when a direct parameter is passed, when a temporary variable is established, it will make an error, so the call move to be displayed, the transfer of ownership, and the return value of the function has been moved, instead of being invoked. shared_ptr

In the beginning of the code, but also a simple use of shared_ptr. shared_ptr name, which allows more than one smart pointer to share "owning" the same heap of memory, because its resources can be shared, it can also share the resources used by the shared_ptr through operator= and other methods. Since shared_ptr is used for reference counting in internal implementations, once a shared_ptr pointer abandons "ownership", other shared_ptr references to the object do not change; only when the reference count is zeroed, shared_ PTR will actually free up the amount of memory space in the heap. For reference counting problem, I no longer summarized here, can refer to the following article:
-  Smart pointer-reference count implementation
- com reference count 1
- com reference count 2
I am here to pay attention to the summary of the use of shared_ptr, and will not shared_ptr to the source level analysis. Another simple code to see some of the shared_ptr applications.

#include <iostream> #include <memory> using namespace std;
    void Func1 (Shared_ptr<int> a) {cout<< "Enter Func1" <<endl;
    cout<< "Ref count:" <<a.use_count () <<endl;
cout<< "Leave Func1" <<endl;
    } shared_ptr<int> Func2 (shared_ptr<int> a) {cout<< "Enter Func2" <<endl;
    cout<< "Ref count:" <<a.use_count () <<endl;
    cout<< "Leave Func2" <<endl;
return A;
    int main () {shared_ptr<int> aObj1 (new int (10));

    cout<< "Ref count:" <<aobj1.use_count () <<endl;
        {shared_ptr<int> aObj2 = aObj1;
    cout<< "Ref count:" <<aobj2.use_count () <<endl;

    } Func1 (AOBJ1);

    FUNC2 (AOBJ1);
    shared_ptr<int> aObj3 = FUNC2 (aObj1);

    cout<< "Ref count:" <<aobj3.use_count () <<endl;
return 0; }

Think about the output of your program alone. The output is as follows:

Ref count:1
ref count:2
Enter FUNC1
ref count:2
Leave Func1
Enter Func2
Ref count:2
Leave Func2
Enter Func2
ref count:2
Leave Func2
ref count:2

shared_ptr point to Array
By default, shared_ptr will call delete for memory release, and when allocating memory using new[], we need the corresponding call delete[] to free up memory, and we need to customize a delete function to correctly use shared_ptr to point to an array. For example:

#include <iostream>
#include <memory>
using namespace std;

Class A
{public
:
    A () {cout<< "constructor" <<endl;}
    ~a () {cout<< "destructor" <<endl;}
};

int main ()
{
    shared_ptr<a> arrayobj (New a[5], [] (A *p) {delete[] p;});

    return 0;
}

The above code does not understand, please refer to this article "lambda expression in C + +" article. If you do need to host an object in a shared way, it may be simpler to use unique_ptr, for example:

#include <iostream>
#include <memory>
using namespace std;

Class A
{public
:
    A () {cout<< "constructor" <<endl;}
    ~a () {cout<< "destructor" <<endl;}
};

int main ()
{
    unique_ptr<a[]> arrayobj (new a[5]);

    return 0;
}

Thread Safety
For the use of shared_ptr in multiple threads, there are several descriptions:

1. The same shared_ptr is read by multiple threads and is thread-safe;
2. The same shared_ptr is written by multiple threads, not thread-safe;
3. The different shared_ptr of shared reference counts are written by multiple threads and are thread-safe. For the 1th, there is nothing to say; for 2nd, the same shared_ptr write in different threads is not thread safe, based on the 3rd, we generally have the following scenarios to achieve thread safety:

For the incoming external shared_ptr object in the thread, a new construct is carried out within threads, for example: sharedptr aobjtmp = outersharedptrobj;

Circular Reference
For smart pointers that are implemented using reference counting, this problem is not always avoided. If there is a code similar to the following, there is a problem with circular references.

class Parent {public:shared_ptr<child> child;}; Class Child {public:shared_ptr<parent> 

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.