- Examples
Explore practical examples of using smart pointers in C++ to manage dynamic memory safely. Understand how shared_ptr manages reference counting, how custom deleters work, and why weak_ptr is needed to break cyclic references. This lesson helps you apply smart pointers to avoid memory leaks and optimize resource handling.
We'll cover the following...
We'll cover the following...
Example 1 #
To get a visual idea of the life cycle of the resource, there is a short message in the constructor and destructor of MyInt (lines 8 - 16).
Explanation #
-
In line 22, we create
MyInt(1998), which is the resource that the smart pointer should address. By usingsharPtr->val, we have direct access to the resource (line 23). -
The output of the program shows the number of references counted. ...