liveBook · Manning

Std::unique_ptr

As explained in Learn C++ by Example

std::unique_ptr is a C++ standard library smart pointer that exclusively owns a dynamically allocated object and destroys it when ownership ends.

std::unique_ptr is a smart pointer that exclusively owns a dynamically allocated object. Its destructor deletes the object by default, so ownership ends automatically when the pointer leaves scope or is reset. section 6.2.2

Use unique_ptr when one object should have one clear owner:

  • Copying is disabled because copying would create a second owner; moving transfers ownership instead. section 6.2.2
  • Store unique_ptr objects in containers to manage the pointed-to objects automatically when the container is destroyed. section 6.2.2
  • Use operator-> to call members of the object owned by a unique_ptr. section 6.2.3
  • Prefer unique_ptr over shared_ptr when shared ownership is unnecessary; shared_ptr adds shared ownership and a control-block count. section 6.2.2

Owning polymorphic blobs

A vector of std::unique_ptr<Blob> can hold different Blob implementations, such as StepperBlob and RandomBlob. The race moves each object through blob->step() and draws its current position through blob->total_steps(). section 6.2.3

Listing 6.13 Using smart pointers in a vector
void very_smart()
{
    std::vector<SmartPointer<Blob>> blobs;
    blobs.emplace_back(make_smart_pointer<StepperBlob>());   #1
}                                                            #2

This compact listing shows a smart-pointer vector taking ownership of a dynamically created StepperBlob and cleaning it up with the vector's lifetime. section 6.2.2

The pointer can also use a custom deleter. A coroutine task uses std::unique_ptr with a deleter that obtains a coroutine handle and calls destroy, allowing the task to follow the rule of zero. section 8.3.4

How Learn C++ by Example covers it

How deep it goes
Explains RAII, deletion, copying, moving, member access, containers, and custom deleters, but not implementation internals.
Examples
Uses smart-pointer vectors, a polymorphic blob race, make_unique construction, and coroutine-handle cleanup.
What it assumes
Assumes raw pointers and dynamic allocation while teaching RAII ownership, move-only behavior, and smart-pointer alternatives.
What you can do after
Apply it via the C++ standard library to express exclusive ownership and automatic cleanup, including custom destruction.
How it connects
Connects unique_ptr with RAII, move semantics, polymorphism, shared_ptr, weak_ptr, custom deleters, coroutines, and the rule of zero.

Also explained in

Compare how 2 books explain std::unique_ptr →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.