MasterofProject

Using C + + real smart pointer unique PTR series - STD:: unique PTR instead of operator new (error: 'unique PTR' is not a member of 'STD')

Label Unique-ptrC++
645 people read comments(0) Collection Report
Classification:

Wrote a lot of articles on the vector blog, in fact, vector is very convenient, but also very simple. But a lot of error prone problems are the elements in the vector is caused by the smart pointer. So I decided to start writing a story about smart pointers, especially the unique_ptr pointer.

This is the beginning, let us use std:: unique_ptr instead of operator new bar!

Still use the program to talk:

#include<iostream>
Int(main)
{
    While(True)
        Int= *xNew Int;
}

Look at the memory in the task manager:
Write the picture here.

At this point the use of smart pointers unique_ptr:

#include<iostream>
#include<memory>
Int(main)
{
    While(True)
        STD: unique_ptr<Int(> xNew Int(Ten));
}

Write the picture here.

Two pictures can clearly see the benefits of smart pointers.

If we are in a timely manner to the traditional pointer, we can achieve the effect of smart pointer:

<iostream> #include
Using Namespace STD;
IntMain () {
    While(True{)
        Int= *xNew Int;
        DeleteX;
}
    Return Zero;
}

Write the picture here.

Here again to share a mistake. On the MAC editor to write c + + code, which uses a unique PTR smart pointer, the code in the vs2015 when, will prompt error:
'unique_ptr' is not a member of 'STD'

The reason is very simple, is the lack of unique_ptr header files:

#include<memory>

Then you may be a problem, when the smart pointer to release the memory of it?
Unique_ptr objects automatically delete the object they manage (using a Deleter) as soon as they themselves areDestroyedAs soon as their orChanges valueBy an eitherOperation assignmentBy an explicit call to orUnique_ptr:: reset.

The next article will start with the unique_ptr's constructor!!

top
One
tread
Zero
Guess you're looking for
View comments
* the above user comments only represent their personal views, does not represent the views or position of the CSDN website
    personal data
    • Visit138398 times
    • Integral:Three thousand eight hundred and sixty-nine
    • Grade
    • Rank:4512nd name
    • Original219
    • Reproduced:15
    • Translation:6
    • Comments:159
    Blog column
    Classification of articles
    Latest comments