Managing exclusive ownership

The unique_ptr class is constructed with a pointer to the object it will maintain. This class provides the operator * to give access to the object, dereferencing the wrapped pointer. It also provides the -> operator, so that if the pointer is for a class, you can access the members through the wrapped pointer.

The following allocates an object on the free store and manually maintains its lifetime:

    void f1()     {        int* p = new int;        *p = 42;        cout << *p << endl;        delete p;     }

In this case, you get a pointer to the memory on the free store allocated for an int. To access the memory--either to write to it or read from it--you dereference the pointer with the * operator. When you are finished with the pointer, you ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.