C++ memory unique_ptr Class
Example
Create a unique_ptr that points to an int:
unique_ptr<int> ptr(new int(25));
cout << *ptr;
Definition and Usage
A unique_ptr is a smart pointer that is the only owner of its memory. The memory is freed automatically when the unique_ptr goes out of scope, for example when the function ends.
You use * to get the value, just like with a normal pointer. A unique_ptr cannot be copied, because there can only be one owner.
The unique_ptr class is defined in the <memory> header file.
Note: Since C++14, you can also write make_unique<int>(25) instead of new int(25).
Syntax
unique_ptr<type> name(new type(value));
type is the data type of the value, like int or string.
Parameter Values
| Parameter | Description |
|---|---|
| value | Optional. The start value of the new memory. |
Technical Details
| Returns: | A unique_ptr object that points to the new memory. |
|---|
Related Pages
Read more about smart pointers in our Smart Pointers Tutorial.