liveBook · Manning

Ownership transfer

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

Ownership transfer is the operation of changing which object is responsible for managing a resource.

Ownership transfer changes which object is responsible for managing a resource. A raw-pointer copy does not transfer ownership: it creates another pointer to the same resource. Deleting through both pointers therefore causes undefined behavior. section 2.8

The double-deletion mistake

In the problematic example, b2 = b1 copies the pointer. b1 then deletes the Buffer, leaving b2 pointing at an already-deleted object; deleting b2 again produces undefined behavior. The intended transfer must be represented explicitly rather than inferred from pointer flow. section 2.8

Listing 2.16 Implementing exclusive ownership using unique_ptr
struct Buffer {
private:
    std::unique_ptr<int[]> data;                            #1
public:
    Buffer() : data(std::make_unique<int[]>(10)) {}         #2
};
 
int main() {
    auto b1 = std::make_unique<Buffer>();                   #3
    auto b2 = std::move(b1);                                #4
    return 0;
}

Use std::unique_ptr for exclusive ownership: make_unique creates the Buffer, and std::move transfers responsibility from b1 to b2. The same pattern manages the Buffer array without a user-written destructor. section 2.8

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

How deep it goes
Explains pointer-copy failure, RAII limitations, and unique_ptr-based correction with pointer and array examples.
Examples
Contrasts copied Buffer pointers that are deleted twice with unique_ptr objects transferred using std::move.
What you can do after
Apply it via std::unique_ptr and std::move to transfer exclusive ownership while avoiding manual resource deletion.
How it connects
Connects ownership transfer with raw pointers, RAII, std::unique_ptr, std::make_unique, and dynamic resources.

Also explained in

Compare how 3 books explain ownership transfer →

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.