- Examples
Explore how to use std::unique_ptr to safely manage object lifecycles and memory in Modern C++. Understand ownership transfer with move semantics, specialized array handling, and how smart pointers automate resource cleanup. This lesson also introduces shared pointers for advanced memory management.
We'll cover the following...
We'll cover the following...
Example 1
Explanation
-
The class
MyInt(line 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, a
std::unique_ptrand return, in line 26, the address of its resourcenew MyInt(1998). Afterward, we move theuniquePtr1to ...