- Examples
The key question of the std::unique_ptr is when to delete the underlying resource. This occurs when the std::unique_ptr goes out of scope or receives a new resource. Let’s look at two use cases to better understand this concept.
We'll cover the following...
We'll cover the following...
Example 1 #
Explanation #
-
The class
MyInt(lines 7 -17) is a simple wrapper for a number. We have adjusted the destructor in line 11 - 13 for observing the life cycle ofMyInt. -
We create, in line 24, an
std::unique_ptrand return, in line 26, the address of its resource,new MyInt(1998). Afterward, we move theuniquePtr1touniquePtr2(line 29). Therefore,uniquePtr2is the owner of the resource. That is shown in the output of ...