liveBook · Manning

Exclusive ownership

As explained in 100 C++ Mistakes and How to Avoid Them

Exclusive ownership is a resource-management property in which exactly one object or owner is responsible for a resource at a time.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Descends from double-delete consequences to RAII, unique_ptr, move semantics, and exception-safe release.
Examples
Uses Buffer deletion, unique_ptr transfer, Page move construction, and Grades resource-management examples.
What it assumes
Assumes basic C++ pointers and destructors while teaching safer ownership management through concrete failures.
What you can do after
Diagnose accidental pointer sharing and implement ownership transfer with unique_ptr, move semantics, and RAII.
How it connects
Connects exclusive ownership with unique_ptr, RAII, move semantics, raw pointers, and shared ownership.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.