Talking about the auto_ptr/shared_ptr/unique_ptr of intelligent pointer

Source: Internet
Author: User
A. Smart pointers 1. Introducing

We usually apply a piece of space like new and leave it to a pointer, and if we say the last thing we forget, it will cause a memory leak. And the advent of smart pointers is the solution to this problem, smart pointers like pointers, but can be used to manage dynamically allocated memory. This chapter explains three kinds of smart pointers:

(1) C++98 proposed, C++11 abandoned auto_ptr
C++11 's new
(2) shared_ptr
(3) Unique_ptr
In C + +, the three are implemented as templates, the following is the use of smart pointers

Tips:
(1) The head file of the smart pointer is #include<memory>
(2) because Unique_ptr and shared_ptr are new smart pointers to c++11, you need to add parameters to support c++11 at compile time
such as g++ Xx.cpp-o xx-std=c++11
(3) Smart pointers in STD domains, you need to add a namespace using namespace std, or add an STD to the smart pointer::

Test1
#include <iostream>
#include <string>
#include <memory>
using namespace STD;

Class A
{public
: a
    (const std::string s): Str (s)
    {
        cout<< "Object created" < <endl;
    }
    ~report ()
    {
        cout<< "Object deleted" <<endl;
    }
    void comment () const
    {
        cout<<str<<endl;
    }
Private:
    std::string str;

int main (int argc, char* const argv[])
{
    //test1:use smart ptr
    {
        std::auto_ptr<report> PS ( New ("Using auto_ptr"));
        Ps->comment ();
    }
    {
        std::shared_ptr<report> PS (New ("Using shared_ptr"));
        Ps->comment ();
    }
    {
        std::unique_ptr<report> PS (New ("Using unique_ptr"));
        Ps->comment ();
    }
    return 0;
}

Execution results

[Root@server10 auto_ptr]#. T 
object created
using Auto_ptr
object deleted
object created
using shared_ptr
Object deleted
object created
using Unique_ptr
object deleted

Within its scope, the constructor and destructor 2 are called separately . On the principle of intelligent pointer

The smart pointer template defines an object that resembles a pointer, assigns the address of the space to the new object, so that when the object expires, its destructor releases it. 3. Smart pointers should avoid deleting non-heap memory

String str ("Hello");
Shared_ptr<string> pstr (&STR);//no!
When Pstr expires, the delete is not heap memory, error
4. Smart pointers and general pointers

Many aspects of the smart pointer are similar to pointers,

(1) You can dereference the operation (*PS)
(2) You can use it to access struct members (PS->PUFFINDEX)
(3) Assign it to a regular pointer to the same type
(4) Assigning a smart pointer object to a smart pointer of the same type (but it involves a security issue with the assignment in "three")
However, the smart pointer is an object that, when it expires, calls its destructor destructor, while the regular pointer, when it points to heap memory, ultimately requires an artificial delete

Note: Assigning a regular pointer to a smart pointer requires a display type conversion, as shown below

    shared_ptr<int> PD;
    int *p = new int;
    PD = Shared_ptr<int> (P);
two. 3 Kinds of intelligent pointers implementation strategy/implementation technology

Two pointers to the same object, the program may have deleted the object two times, so that the program core DUMPD, that is, we often say that the segment error. Before speaking of C + + assignment statements, we talked about deep copies, so that two pointers point to different objects, one of which is a copy of another object. This is a workaround, and Auto_ptr/shared_ptr/unique_ptr uses a different strategy.

(1) Auto_ptr and UNIQUE_PTRC adopt the ownership (ownership) concept, which can only be owned by a smart pointer for a particular object, so that only the destructor of the smart pointer that owns the object deletes the object, and then, to be aware, Assignment operations transfer the right to operate.
Although both auto_ptr and unique_ptr adopt this strategy, the UNIQUE_PTR strategy is more stringent. When this occurs, the program compiles an error, and auto_ptr the core dumped in the execution phase.
(2) shared_ptr adopts a reference counting (reference count) strategy, for example, when assigning a value of +1, when the pointer expires, count-1. Only when the count is 0 o'clock, the last pointer expires, is destructor.

Each strategy has its purpose. The following code to analyze its pros and cons: three. Smart pointers to the pros and cons of 1.unique_ptr than auto_ptr excellent 1.1 advantages 1:unique_ptr than auto_ptr more secure (1) Auto_ptr will happen.

Test2
auto_ptr<report> P1[5] =
    {
        auto_ptr<report> (new ("Using Auto_ptr")), 
        Auto_ptr<report> (The new ("Using Auto_ptr")), 
        auto_ptr<report> (The new ("Using Auto_ptr")), 
        auto_ptr<report> (New ("Using Auto_ptr")), 
        auto_ptr<report> (New ("Using Auto_ptr") ) 
    };
    auto_ptr<report> P2 = p1[2];//#1 for
    (int i=0; i<5; ++i)
    {
        p1[i]->comment ();
    }

Execution results

[Root@server10 auto_ptr]#. T 
object created
object created object created
object
created Object created
using auto_ptr 0
using auto_ptr 1
segmentation Fault (core dumped)

Similar to Test2 code, (p1[2] gives the title of the case to the P2, and p1[2] is the null pointer, causing the core p1[2 to print the value of the dumped) (2) unique_ptr handling the situation

smrtptrs.cpp:In function ' int main (int, char* const*) ':
smrtptrs.cpp:71:33:error:use of deleted function ' Std::uniq UE_PTR<_TP, _dp>::unique_ptr (const STD::UNIQUE_PTR<_TP, _dp>&) [with _TP =; _DP = std::d efault_ DELETE<REPORT>] '
     unique_ptr<report> p2 = p1[2];
                                 ^
in file included from/usr/include/c++/4.8.2/memory:81:0, from
                 smrtptrs.cpp:3:
/usr/include/c++/4.8.2 /bits/unique_ptr.h:273:7: error:declared here
       unique_ptr (const unique_ptr&) = delete;
       ^

When the auto_ptr in Test2 is replaced by unique_ptr, the compiler reports the above error directly, and the compiler thinks that the # is illegal and avoids the situation where the p1[2 will be directed to invalid data.
This is also why the container algorithm prohibits the use of auto_ptr, but allows the use of unique_ptr .
Therefore,Unique_ptr is more secure than auto_ptr .
Of course unique_ptr is not allowed to assign a value, it allows the source unique_ptr to be a temporary right value , as in the following example:

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

unique_ptr<string> demo1 (const char* s)
{
    cout<< "DEMO1 TEST" <<endl;
    Unique_ptr<string> Temp (new string (s));
    return temp;
}

Auto_ptr<string> Demo2 (const char* s)
{
    cout<< "DEMO2 TEST" <<endl;
    Auto_ptr<string> Temp (new string (s));
    return temp;
}
int main (int argc, char* const argv[])
{
#if __unique_ptr__
    unique_ptr<string> PS;
    PS = demo1 ("Hello");
#endif return
    0;
}

So assigning a temporary smart pointer to another smart pointer doesn't leave a dangerous hanging pointer on how to safely reuse unique_ptr pointers

To safely reuse a unique_ptr pointer, you can assign it a new value. C + + provides a Std::move () method for it.

    Unique_ptr<string> pu1 (New string ("Nihao"));
    Unique_ptr<string> pu2;
    PU2 = Std::move (PU1);//move
    cout<<*pu1<<endl;//Assign new value

and auto_ptr because the policy is not unique_ptr strict, do not need to use the Move method

    Auto_ptr<string> pu1, PU2;
    PU1 = Demo2 ("uniquely special");
    PU2 = pu1;
    PU1 = Demo2 ("and more");
    cout<<*pu2<<*pu1<<endl;

Because Unique_ptr uses C++11 's new move constructor and right value reference, you can distinguish between safe and unsafe usage. 1.2 advantages 2:unique_ptr, compared with auto_ptr and UNIQUE_PTR, provides variants that can be used in arrays

Auto_ptr and shared_ptr can be used with new, but not with new[], but unique_ptr can be used with new[]

Unique_ptr<double[]> PDA (new double (5));
2. In contrast, shared_ptr's strategy is more witty.

Since shared_ptr uses a reference-counting policy, it is not necessary to consider a null value for the source smart pointer when assigning a value

    shared_ptr<string> P1 (New string ("Hello"));
    shared_ptr<string> P2;
    P2 = p1;
    cout<< "P1" <<*p1<<endl<< "P2" <<*p2<<endl;
Four. Select the smart pointer

The sixth edition of "C + + Primer Plus" P673 in detail, here is a brief explanation

#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
#include <stdlib.h>
using namespace std;

unique_ptr<int> make_int (int n)
{return
    unique_ptr<int> (new int (n));
}

void Show (Unique_ptr<int> & PI)     //pass by reference
{
    cout<< *pi << ';
}

int main ()
{
    vector<unique_ptr<int> > VP (5);
    for (int i = 0; i < vp.size (); ++i)
    {
        Vp[i] = Make_int (rand ()% 1000);//copy temporary unique_ptr
    }
    Vp.push_back (Make_int (rand ()% 1000))//ok because ARG is temporary for_each (Vp.begin ()
    , Vp.end (), show);
    Unique_ptr<int> Pup (Make_int (rand ()% 1000));
   Shared_ptr<int> spp (PUP);//not allowed. The pup is Lvalue
    shared_ptr<int> SPR (Make_int (rand ()% 1000));

    return 0;
}

(1) When multiple objects point to the same object's pointer, you should choose shared_ptr
(2) with the new application of memory, return to the pointer to this memory, select Unique_ptr is good
(3) When satisfying unique_ptr requirements, the premise is that there is no ambiguous assignment, you can also use the auto_ptr
(4) as shown in the code above, Unique_ptr is the right value (not exactly the same as the inability to address), can be assigned to shared_ptr

That ' s all!

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.