RAII and single ownership
Tie resource release to object lifetime so every exit path has an owner.
Resource lifetime
RAII means a resource is acquired and represented by an object whose destructor releases it. The resource may be memory, a lock, a file or a peripheral reservation. Deterministic destruction avoids duplicating cleanup logic across early returns.
Single ownership
A unique_ptr owns one dynamically allocated object by default. It cannot be copied but can transfer ownership by moving. Calling get gives a non-owning pointer, not a second owner. Embedded projects may forbid dynamic allocation; RAII also works for statically allocated resources.
Move and validity
Moving is an operation on an object, not a promise that bytes are simply relocated. A moved-from unique_ptr is empty. For other types, use their documented moved-from guarantees. Keep ownership explicit in APIs.
#include <memory>
auto owner = std::make_unique<int>(42);
auto next = std::move(owner);
// owner is empty; next owns the int.Follow each transition
Acquire
One owner acquires the resource.
Conceptual sequence. Timing is slowed for learning; it is not a hardware measurement.
Your investigation
Two objects both close the same resource after a shallow copy. How would you change ownership?
Reveal the investigation checklist
- Identify the single responsible owner.
- Delete copying or implement meaningful deep-copy semantics.
- Implement safe move semantics if transfer is needed.
- Verify cleanup on early returns.
After moving a unique_ptr into another unique_ptr, which owns the object?
Answer the knowledge check correctly to complete this lesson.
Think through RAII and single ownership
Ask for an explanation, an automotive example or a question that tests your understanding.
Checking mentor availability…