Search⌘ K

- 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...

Example 1 #

C++
// uniquePtr.cpp
#include <iostream>
#include <memory>
#include <utility>
struct MyInt{
MyInt(int i):i_(i){}
~MyInt(){
std::cout << "Good bye from " << i_ << std::endl;
}
int i_;
};
int main(){
std::cout << std::endl;
std::unique_ptr<MyInt> uniquePtr1{ new MyInt(1998) };
std::cout << "uniquePtr1.get(): " << uniquePtr1.get() << std::endl;
std::unique_ptr<MyInt> uniquePtr2;
uniquePtr2= std::move(uniquePtr1);
std::cout << "uniquePtr1.get(): " << uniquePtr1.get() << std::endl;
std::cout << "uniquePtr2.get(): " << uniquePtr2.get() << std::endl;
std::cout << std::endl;
{
std::unique_ptr<MyInt> localPtr{ new MyInt(2003) };
}
std::cout << std::endl;
uniquePtr2.reset(new MyInt(2011));
MyInt* myInt= uniquePtr2.release();
delete myInt;
std::cout << std::endl;
std::unique_ptr<MyInt> uniquePtr3{ new MyInt(2017) };
std::unique_ptr<MyInt> uniquePtr4{ new MyInt(2022) };
std::cout << "uniquePtr3.get(): " << uniquePtr3.get() << std::endl;
std::cout << "uniquePtr4.get(): " << uniquePtr4.get() << std::endl;
std::swap(uniquePtr3, uniquePtr4);
std::cout << "uniquePtr3.get(): " << uniquePtr3.get() << std::endl;
std::cout << "uniquePtr4.get(): " << uniquePtr4.get() << std::endl;
std::cout << std::endl;
}

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 of MyInt.

  • We create, in line 24, an std::unique_ptr and return, in line 26, the address of its resource, new MyInt(1998). Afterward, we move the uniquePtr1 to uniquePtr2 (line 29). Therefore, uniquePtr2 is the owner of the resource. That is shown in the output of ...