Skip to main content

std::unique_ptr in c++ | C++ 11

std::unique_ptr :

C++11 introduces std::unique_ptr, defined in the header .

It is a container for a raw pointer. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the std::move function can be used to transfer ownership of the contained pointer to another unique_ptr.

Reason for it won’t allow copy :
A unique_ptr cannot be copied because its copy constructor and assignment operators are explicitly deleted.

std::unique_ptr p1(new int(5));
std::unique_ptr p2 = p1; //Compile error.
std::unique_ptr p3 = std::move(p1); //Transfers ownership. p3 now owns the memory and p1 is set to nullptr.

p3.reset(); //Deletes the memory.

p1.reset(); //Does nothing.



Complate Example: 


// C++ program to illustrate the use of unique_ptr
#include
#include
using namespace std;
class A
{
public:
    void show()
    {
        cout<<"A::show()"<
    }
};
int main()
{
    unique_ptr p1 (new A);
    p1 -> show();
    // returns the memory address of p1
    cout << p1.get() << endl;
    // transfers ownership to p2
    unique_ptr p2 = move(p1);
    p2 -> show();
    cout << p1.get() << endl;
    cout << p2.get() << endl;
    // transfers ownership to p3
    unique_ptr p3 = move (p2);
    p3->show();
    cout << p1.get() << endl;
    cout << p2.get() << endl;
    cout << p3.get() << endl;
    return 0;
}



Output:

A::show()
0x1c4ac20
A::show()
0          // NULL
0x1c4ac20
A::show()
0          // NULL
0          // NULL
0x1c4ac20

Comments