TATVONYour account ↗
C++ for embedded engineers / 18 MIN

RAII and single ownership

Tie resource release to object lifetime so every exit path has an owner.

01

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.

02

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.

03

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.
SEE THE SYSTEM

Follow each transition

1 / 4
STEP 1

Acquire

One owner acquires the resource.

Conceptual sequence. Timing is slowed for learning; it is not a hardware measurement.

PUT IT TO WORK

Your investigation

Two objects both close the same resource after a shallow copy. How would you change ownership?

Reveal the investigation checklist
  1. Identify the single responsible owner.
  2. Delete copying or implement meaningful deep-copy semantics.
  3. Implement safe move semantics if transfer is needed.
  4. Verify cleanup on early returns.
CHECK YOUR UNDERSTANDING

After moving a unique_ptr into another unique_ptr, which owns the object?

Choose one answer
Sign up to save your progress →

Answer the knowledge check correctly to complete this lesson.

TATVON AI MENTOR

Think through RAII and single ownership

Ask for an explanation, an automotive example or a question that tests your understanding.

Checking mentor availability…