Learn C++ · lesson 36 of 61 · about 8 minutes
Smart Pointers
A companion joins the hero: own it safely with std::unique_ptr and std::make_unique, and hand it over with std::move.
What you'll learn
- Create a unique_ptr with make_unique
- Transfer ownership with std::move
- Know when shared_ptr fits
A companion
In the dungeon, a companion joins the hero. Above main, struct Companion groups a companion's name and courage into one type. The hero owns the companion through auto companion = std::make_unique<Companion>(Companion{petName, 3}); and reaches its name with companion->name. When the guard offers to look after it, the hero can say give: guarded = std::move(companion); hands the companion over, so companion is empty afterwards and the hero walks on alone. Nobody has to delete anything: whoever owns the companion when the program ends cleans it up.
Ownership
std::unique_ptr<T> (#include <memory>) owns one object and deletes it automatically when the pointer goes away. There's no delete to forget.
auto p = std::make_unique<int>(42);creates it- Use
*pandp->memberlike a normal pointer - It can't be copied (there's only one owner), but it can be moved:
auto q = std::move(p);leaves p empty std::shared_ptrallows several owners and deletes when the last one goes
Automatic clean-up
#include <iostream>
#include <memory>
#include <string>
struct Pet {
std::string name;
explicit Pet(std::string n) : name(std::move(n)) { std::cout << name << " created\n"; }
~Pet() { std::cout << name << " cleaned up\n"; }
};
int main() {
auto phoebe = std::make_unique<Pet>("Phoebe");
std::cout << "Hello, " << phoebe->name << "\n";
auto owner = std::move(phoebe);
std::cout << std::boolalpha << (phoebe == nullptr) << "\n";
std::cout << "end of main\n";
}Output
Phoebe created
Hello, Phoebe
true
end of main
Phoebe cleaned upTip
The ~Pet() function is a destructor: it runs automatically when an object is destroyed. unique_ptr calls it for you at exactly the right moment.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.