C++ / CHAPTER 10
Resource ownership with RAII
AdvancedGive resources a clear owner and transfer exclusive ownership explicitly.
By the end of this chapter
- Explain automatic cleanup at scope exit
- Transfer a unique_ptr with std::move
- Avoid reading through an empty owner
The idea
Start with references, scopes, and object lifetimes. Resource management becomes easier when an object owns a resource and its destructor releases it. This pattern is called RAII. Standard containers already apply it to their storage. For a separately allocated object with one owner, unique_ptr expresses exclusive ownership and performs cleanup when the owner is destroyed, including during normal exception unwinding.
A unique_ptr cannot be copied into a second independent owner. Moving transfers its ownership; after a successful move the source unique_ptr is empty. std::move itself is a cast that permits move-aware operations, not a universal promise that every object becomes empty. Here the receiving unique_ptr performs the actual transfer. Prefer make_unique to a raw allocation, and borrow through references when ownership should stay with the caller.
#include <iostream>
#include <memory>
#include <utility>
int main(){auto first=std::make_unique<int>(12); auto second=std::move(first);
std::cout<<static_cast<bool>(first)<<" "<<*second<<"\n";}0 12
The second unique_ptr owns the integer. The first is empty and can be tested, but must not be dereferenced.
Try it yourself
Design a function signature that accepts ownership of one unique_ptr<int> and returns an updated owner.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING