Quiz 11 — Answers¶
Q1 — A. RAII ties a resource's lifetime to an object's: acquire in the constructor, release in the destructor, so cleanup happens on every exit path automatically.
Q2 — False. std::unique_ptr is move-only. Copying it is a compile error, which is the
whole point — it cannot have two owners. Use std::move to transfer ownership.
Q3 — A, C. A library that owns its items (A) and a factory's returned shape (C) are
sole ownership. A shared logger (B) is shared_ptr; an observer that must not keep the
subject alive (D) is weak_ptr.
Q4 — a +x b -x c. The Res is constructed inside the block (+x) and destroyed at
the closing brace (-x), before c prints. No delete appears because unique_ptr does
it.
Q5 —
weak_ptr does not own and does not affect use_count, so it is 1. After sp.reset() the
object is destroyed, so wp.lock() returns an empty pointer and the program prints gone.
Always lock() and test before use.
Q6 — a->neighbour = b; b->neighbour = a; gives each node a shared_ptr to the other,
so each keeps the other alive and neither is freed (a reference cycle). Fix: make one
direction a std::weak_ptr:
struct Node {
std::shared_ptr<Node> next; // owns
std::weak_ptr<Node> previous; // observes, closes the cycle
};
Q7 — on 1 on 2 | off 1 off 2 end (this toolchain). shelf.clear() destroys each
unique_ptr, which deletes its Device. The destruction order of elements in a vector
on clear() is not specified by the standard, so do not depend on it.
Q8 — Because weak_ptr does not participate in ownership — it is a way to observe
an object managed by shared_ptr without keeping it alive. Only owning references
(shared_ptr) count toward use_count.
Q9 — Delete the copy constructor and copy assignment: two guards would try to close the same session, violating "no two jobs at once". Keep (default) the move constructor and move assignment: a job may hand its session to another, and the moved-from guard becomes harmless. The destructor closes the session on every path.
Q10 — (1) Shared ownership is harder to reason about — you must know every owner to
know when the object dies, and two shared_ptrs pointing at each other form a cycle that
never frees. (2) The reference count has a runtime and memory cost, and it hides the
ownership question instead of answering it. Prefer unique_ptr (or a value) until you can
name why ownership is genuinely shared.
Marking. One point per question (Q3 all-or-nothing). Then read Marking Yourself.