- Examples
Learn how to use C++ smart pointers through examples that demonstrate unique_ptr ownership, resource swapping, array management, and lifecycle handling. Understand key smart pointer operations and how they ensure safe and efficient memory management in your code.
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 ...