`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_uniqueinstead of writingnew. unique_ptrcannot be copied.unique_ptrcan be moved withstd::move.- Passing
unique_ptrby value usually means ownership transfer. - Use raw pointers or references only for non-owning access.
Common Mistakes
- Trying to copy a
unique_ptr. Copying is disabled because ownership is exclusive. - Calling
deletemanually on the managed object. The smart pointer owns cleanup. - Using
shared_ptrwhen one owner is enough. Shared ownership adds cost and complexity. - Returning references to destroyed owned objects. Non-owning views must not outlive the owner.
Quick Check
- Why does
Carreceive the engine withstd::unique_ptr<Engine>? - What happens to the engine when the
Caris destroyed?
Viva Answer
std::unique_ptr represents exclusive ownership. It deletes the owned object automatically and can transfer ownership through move semantics.