Exclusive ownership means exactly one object manages a resource at a time. Copying a raw pointer accidentally creates shared ownership, making deletion ambiguous and potentially causing undefined behavior. section 2.8
Use ownership-aware designs to make responsibility explicit:
- Represent dynamically allocated resources with std::unique_ptr when one owner should manage them. section 2.8
- Transfer ownership with std::move rather than copying the owning pointer. section 2.1 section 2.8
- Use RAII so the owning object releases the resource automatically, including during exceptional control flow. section 10.5
From double deletion to explicit transfer
In the failing pattern, b2 copies b1 and both pointers appear responsible for the same Buffer; deleting b1 and then b2 can trigger undefined behavior. The corrected pattern stores the array in std::unique_ptr, creates b1 with make_unique, and moves ownership into b2, leaving one active owner.
Listing 2.2 A uniqueness-preserving assignment operator with negligible cost
class TextSection {
// assume a clever implementation
};
class Page {
private:
TextSection* headers;
TextSection* body;
public:
Page(TextSection* h) : headers(h), body(new TextSection()) {}
Page(const Page& o) : headers(o.headers), body(new #1
TextSection(*o.body)) {}
Page(Page&& o) : headers(o.headers), body(o.body) { #2
o.headers = nullptr; #3
o.body = nullptr;
}
~Page() { delete body; }
};
int main() {
Page p1(new TextSection());
Page p2 = std::move(p1); #4
return 0;
}
Compare copy-based and move-based Page construction: the move constructor transfers pointers and nulls the source without duplicating the resource. section 2.1
