All Courses
OOP: RAII AND OWNERSHIP

`unique_ptr`

Concept Definition

std::unique_ptr is a smart pointer for exclusive ownership. Exactly one unique_ptr owns the object at a time. When the owner is destroyed, the owned object is deleted automatically.

Think of a single library card assigned to one student. The card can be transferred, but two students cannot both be the official holder at the same time.

Why It Matters

Most beginner memory leaks come from unclear ownership. std::unique_ptr makes ownership visible in the type system. It cannot be copied, so the compiler prevents accidental double ownership.

Use unique_ptr as the default owning pointer when an object must live on the heap. It is usually better than raw new and often simpler than shared_ptr.

Syntax Block

auto object = std::make_unique<Type>(); // create exclusive owner
std::unique_ptr<Type> next = std::move(object); // transfer ownership

Explained Code

Example: Car Owns One Engine

#include <memory> // std::unique_ptr, std::make_unique
#include <string> // std::string

class Engine {
private:
    std::string model;                       // engine data

public:
    explicit Engine(std::string engineModel) : model(std::move(engineModel)) {} // initialize
    const std::string& getModel() const { return model; } // safe read access
};

class Car {
private:
    std::unique_ptr<Engine> engine;          // car exclusively owns engine

public:
    explicit Car(std::unique_ptr<Engine> ownedEngine)
        : engine(std::move(ownedEngine)) {}  // ownership moves into car

    const Engine& getEngine() const { return *engine; } // expose non-owning view
};

The Car owns the Engine. Outside code can inspect the engine through a reference, but it does not own the engine.

Key Points / Rules

  • Use std::make_unique instead of writing new.
  • unique_ptr cannot be copied.
  • unique_ptr can be moved with std::move.
  • Passing unique_ptr by value usually means ownership transfer.
  • Use raw pointers or references only for non-owning access.

Common Mistakes

  1. Trying to copy a unique_ptr. Copying is disabled because ownership is exclusive.
  2. Calling delete manually on the managed object. The smart pointer owns cleanup.
  3. Using shared_ptr when one owner is enough. Shared ownership adds cost and complexity.
  4. Returning references to destroyed owned objects. Non-owning views must not outlive the owner.

Quick Check

  1. Why does Car receive the engine with std::unique_ptr<Engine>?
  2. What happens to the engine when the Car is destroyed?

Viva Answer

std::unique_ptr represents exclusive ownership. It deletes the owned object automatically and can transfer ownership through move semantics.