Unit 4 of 9 · about 6 hours · explain, implement
Storage duration, RAII, smart pointers and move semantics
A buffer can be correctly indexed and still be dead. RAII makes cleanup follow ownership, including failure paths that are easy to miss with manual deletion.
You'll be able to
- Distinguish storage duration from the lifetime and ownership of an object in that storage.
- Predict destruction and resource release through normal returns and caught exceptions.
- Implement an owning buffer with independent-copy, ownership-transfer and checked-access tests.
Covers
Read
In this order, only the parts listed
0 of 6 done
- Stack vs HeapAlgoMaster C++
The Stack: Automatic and LIFO; The Heap: Dynamic and Manual; When to Use the Stack vs the Heap
Skip address-region diagrams and Performance Differences. Automatic and dynamic storage duration are language concepts, not guarantees about placement or allocation speed.
- RAII PatternAlgoMaster C++
The Core Idea through Hand-Rolled Cleanup vs RAII Under Exceptions; A Note on the Rule of Three; Almost Always RAII
- Exclusive ownershipAlgoMaster C++
Constructing a
unique_ptr; Move-Only Semantics; The Common Operations; Arrays withunique_ptr<T[]> - Shared ownership and observersAlgoMaster C++
When Shared Ownership Actually Makes Sense; The Control Block; Thread Safety, Precisely; What This Chapter Does Not Cover
- Copy and move contractsAlgoMaster C++
The Move Constructor Signature through When the Compiler Generates a Move Constructor; A Complete Example: Cart with Move and Copy
Skip the introductory claim that return-by-value necessarily copies and Exercise 7's unconditional
noexceptrule. Copy elision can remove transfers, andvectorcan move a noncopyable element even if its move may throw. - RAII and special membersC++ Core Guidelines
R.1: Manage resources automatically using resource handles and RAII; C.20: If you can avoid defining default operations, do; C.21: If you define or delete any copy, move, or destructor function, define or delete them all
Focus on
- An automatic smart-pointer handle can own a dynamically allocated object. The handle and the allocation have separate lifetimes.
- Scope exit and exception unwinding destroy fully constructed automatic objects in reverse construction order. A constructor that throws does not run that object's destructor, but already constructed members and bases are unwound.
- Prefer
vectorand the Rule of Zero for ordinary buffers. If you manage a raw resource, state copy and move contracts for constructors and assignment, and leave the moved-from object safe to destroy. unique_ptrexpresses exclusive ownership.shared_ptrshares ownership, not synchronization of the pointee;weak_ptrobserves without forming a strong ownership cycle.
Common mistakes · 3
std::moveis a cast that enables move overloads. It does not itself transfer resources; moving from aconstobject can select a copy.- A
shared_ptrreference count does not collect strong cycles or protect mutable data from concurrent access. - RAII is not a promise of cleanup after process termination,
std::abortor every uncaught exception. Test ordinary scope exit and caught unwinding.
Try it yourself
Closed-book, before checking anything
-std=c++20 -O0 -g, construct two local logging guards A then B inside a try block and throw std::runtime_error to an outer catch. Print only names from destructors and 'catch' from the handler: the sequence is B A catch. Separately move make_unique<int>(7) into a second unique_ptr and assert the first is null and the second holds 7. Implement a vector-backed Buffer with a deep-copy contract, a custom move that resets the source to an empty state, and access that throws std::out_of_range for i >= size(). Check copy independence, move construction, move assignment, self-assignment, empty access and a caught exception after allocation. Keep the checks active in optimized builds; do not rely only on assert when NDEBUG is set.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A constructor acquires two resources but the second acquisition throws. How should the first be protected?Answer
Place it in an already constructed RAII member or local guard. That guard is destroyed during unwinding even though the enclosing object's destructor does not run.
2.Does copying a raw owning pointer produce an independent buffer?Answer
No. It copies the address. Either duplicate the storage explicitly, prohibit copying, or use a value-owning member such as vector.
3.After moving a
unique_ptrinto another, which one owns the object?AnswerThe destination owns it; the source is null. This specific guarantee is stronger than assuming all moved-from types are empty.
4.Must a return-by-value function always call a copy or move constructor?Answer
No. Copy elision can avoid both. C++17 guarantees elision for certain prvalue cases; named return value optimization is permitted but not generally mandatory.
Practice
- AlgoMaster Exercise: RAII
Exercises 1 to 5: scoped release, closing on every return path, unlocking during unwinding, rolling back an uncommitted transaction and restoring a global setting after an exception
Predict the printed acquire and release order before running each one.
- AlgoMaster Exercise: Copy-and-Swap Idiom
Exercises 2 to 4: deep copy for copy-swap assignment, one by-value operator for copy and move, and leaving the target unchanged when copying throws
Carry the deep-copy and failed-copy checks into the owning
Buffertests.
You're done when
You predict the guard destruction trace and your buffer tests demonstrate independent copies, an explicitly empty moved-from state and cleanup through a caught exception.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 8 more in the section
- AlgoMaster C++AlgoMaster · primary
Use the sections on compilation, pointers and references, memory, RAII and smart pointers, copy and move, STL containers, templates, errors, concurrency and paired exercises. Skip competitive-programming breadth already covered in Algorithms.
- C++ Core GuidelinesStandard C++ Foundation community · required
Use the Philosophy, Interfaces, Resource management, Expressions, Containers and concurrency rule groups to review ownership and safety decisions in the native component.
Also in this section
- cppreferencecppreference community · support
Consult language lifetime, object model, value categories, memory model, atomics, containers and iterator invalidation while reading or modifying code.
- Clang AddressSanitizer and UndefinedBehaviorSanitizerLLVM · required
Compile seeded memory defects with AddressSanitizer and UndefinedBehaviorSanitizer, preserve the reports, repair the root cause and keep regression tests.
- pybind11 documentationpybind11 project · required
Follow First steps and NumPy support to expose one small native function with explicit shape, dtype, stride, ownership, GIL and exception behavior.
- CMake tutorialCMake · support
Use the introductory steps for targets, libraries, testing and install rules. Produce one clean debug build and one optimized build without copied one-off commands.
- Algorithmica - AoS and SoASergey Slotin · support
Read the AoS and SoA experiment for a measured case where keeping each record together wins, the counterpart to a single-field scan.
- `ld.so`: dynamic linker/loaderLinux man-pages project · support
Read DESCRIPTION, Dynamic string tokens and
LD_DEBUGto distinguish link-time symbols from runtime shared-library discovery on Linux. - Memory Layout TransformationsIntel · support
Read Overview and Topics through AOS Form and SOA Form for field-wise access and locality trade-offs. Skip Intel array-notation syntax and the LIBOR example.
- GDB manual: BacktracesGNU Project · support
Use section 8.2 for frame numbers,
bt,bt -fulland optimized-out arguments when inspecting a native failure.