Lesson 5 of 7
Ownership Model & RAII Patterns
The single most important design decision in C++ is **who owns what**. The ownership model determines: when is memory freed, who is responsible, and what happens on exceptions. The three ownership patterns are: **sole ownership** (`unique_ptr`), **shared ownership** (`shared_ptr`), and **non-ownership** (raw pointer/reference for observers). RAII generalises resource management beyond memory: file handles, mutexes, database connections, sockets - anything with an open/close lifecycle.
Ownership Patterns - RAII for Non-Memory Resources
#include <iostream>
#include <memory>
#include <mutex>
#include <fstream>
#include <string>
#include <stdexcept>
// ── RAII for mutex - std::lock_guard ─────────────────────────
std::mutex g_mutex;
void thread_safe_print(const std::string& msg) {
std::lock_guard<std::mutex> lock(g_mutex); // acquire on construction
std::cout << msg << "
";
// lock destroyed on scope exit → mutex released automatically
// No need for manual unlock() even if exception thrown
}
// ── RAII file wrapper (educational - use std::fstream in real code) ──
class ScopedFile {
FILE* fp_;
public:
ScopedFile(const char* path, const char* mode)
: fp_(fopen(path, mode))
{
if (!fp_) throw std::runtime_error(std::string("Cannot open: ") + path);
}
~ScopedFile() { if (fp_) fclose(fp_); } // guaranteed cleanup
ScopedFile(const ScopedFile&) = delete;
ScopedFile& operator=(const ScopedFile&) = delete;
ScopedFile(ScopedFile&& o) noexcept : fp_(o.fp_) { o.fp_ = nullptr; }
FILE* get() const { return fp_; }
bool valid() const { return fp_ != nullptr; }
};
// ── Ownership decision flowchart ─────────────────────────────
// Q: Does this function need to keep the object alive?
// No → Pass const T& (observer)
// Yes → Does it share ownership?
// No → unique_ptr<T> (sole owner)
// Yes → shared_ptr<T> (shared owner)
//
// Q: Does this pointer/ref survive its owner?
// No → raw pointer/reference is fine (observer)
// Yes → shared_ptr / rethink design
// ── Example: Observer does not own ───────────────────────────
class EventSystem {
std::vector<std::unique_ptr<std::string>> event_log_;
std::string* last_event_ = nullptr; // observer pointer - no ownership
public:
void add_event(std::string evt) {
event_log_.push_back(std::make_unique<std::string>(std::move(evt)));
last_event_ = event_log_.back().get(); // observe without owning
}
const std::string* last_event() const { return last_event_; }
void print_log() const {
for (const auto& e : event_log_)
std::cout << " " << *e << "
";
}
};
// ── Exception safety levels ───────────────────────────────────
// nothrow: never throws - all destructors, swap, move
// strong: rollback on exception - transactional
// basic: no leak/corruption on exception, but state may change
// none: may leak or corrupt - unsafe code, never acceptable
int main() {
thread_safe_print("Hello from thread-safe print");
try {
ScopedFile f{"output.txt", "w"};
fputs("RAII file write
", f.get());
std::cout << "File written (closes automatically)
";
} catch (const std::runtime_error& e) {
std::cerr << e.what() << "
";
}
EventSystem events;
events.add_event("user_login");
events.add_event("data_loaded");
events.print_log();
if (auto* last = events.last_event()) {
std::cout << "Last: " << *last << "
";
}
return 0;
}Common Mistakes
- Observer raw pointer outliving the owner - `const std::string* last_event_` is fine as long as the `EventSystem` owns `event_log_` and the pointer is never stored beyond the EventSystem's lifetime. Don't store raw observer pointers in objects that outlive the owner.
- `std::lock_guard` vs `std::unique_lock` - `lock_guard` is for simple RAII lock/unlock. `unique_lock` supports deferred locking, try-lock, and transfer. For simple critical sections, always use `lock_guard`.
- Exception safety with `new` in multi-arg functions - `f(new A(), new B())` - if `new B()` throws, `new A()` may have already allocated but `f` is never called so nothing deletes `A`. Use `make_unique`/`make_shared` which are exception-safe.
Tip
Tip
Practice Ownership Model RAII Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Binding system resources to object lifetime for deterministic cleanup
Practice Task
Note
Practice Task - (1) Write a working example of Ownership Model RAII Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Ownership Model RAII Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- The single most important design decision in C++ is **who owns what**.
- Observer raw pointer outliving the owner - `const std::string* last_event_` is fine as long as the `EventSystem` owns `event_log_` and the pointer is never stored beyond the EventSystem's lifetime. Don't store raw observer pointers in objects that outlive the owner.
- `std::lock_guard` vs `std::unique_lock` - `lock_guard` is for simple RAII lock/unlock. `unique_lock` supports deferred locking, try-lock, and transfer. For simple critical sections, always use `lock_guard`.
- Exception safety with `new` in multi-arg functions - `f(new A(), new B())` - if `new B()` throws, `new A()` may have already allocated but `f` is never called so nothing deletes `A`. Use `make_unique`/`make_shared` which are exception-safe.
Finished this lesson?