Search⌘ K
AI Features

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

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 (line 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, a 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 the program in lines 30 and 31.

  • In line 37, the local std::unique_ptr ...