# Smart pointers: unique_ptr and shared_ptr

> What are smart pointers? Explain uniqueptr and sharedptr, when to use each, and why makeunique and makeshared are preferred over new.

Canonical: https://www.internhack.in/learn/interview/cpp-interview/cpp-smart-pointers
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What are smart pointers? Explain unique_ptr and shared_ptr, when to use each, and why make_unique and make_shared are preferred over new.

## Answer

Smart pointers are RAII applied to dynamic memory, and using them well is the fastest way to remove 90 percent of manual memory bugs from C++ code. Let's look at what each one promises.

std::unique_ptr expresses exclusive ownership: exactly one unique_ptr owns an object at a time, and when it is destroyed, the object is deleted. It is not copyable (copy constructor is deleted) but is movable, so ownership can be transferred, for instance when returning from a function or pushing into a container with std::move. Think of it as the only key to a locker: you can hand the key over, but you cannot photocopy it. It has essentially zero overhead: with the default deleter it is the same size as a raw pointer and as fast. Use it as your default choice for owning a heap object, including polymorphic objects (unique_ptr<Base>, provided Base has a virtual destructor) and the pimpl idiom. There is an array form, unique_ptr<T\[\]>, that calls delete\[\].

std::shared_ptr expresses shared ownership: many shared_ptrs can point to the same object, and it is destroyed when the last owner goes away. Internally it keeps a control block with an atomic strong reference count, a weak count and the deleter, so a shared_ptr is typically two pointers wide, and copying it involves atomic increments. The atomic operations make reference counts thread-safe (though the pointed-to object itself is not), but they cost something. So do not default to shared_ptr; use it when ownership is truly shared, for example a cache entry used by several consumers whose lifetimes are not nested.

Why make_unique and make_shared? First, exception safety in older code: 'f(std::shared_ptr<T>(new T), g())' could leak if g threw between the new and the shared_ptr construction, depending on evaluation order. Second, make_shared performs a single allocation that holds both the object and control block, which is faster and more cache friendly than shared_ptr<T>(new T), which does two. Third, it avoids writing the type name twice and avoids naked new. There are caveats: make_shared cannot use a custom deleter, and the memory of the object is kept alive until the last weak_ptr disappears because it lives in the same block.

A couple of rules to mention. Pass a smart pointer by value or reference to a function only when that function participates in ownership; if it only uses the object, pass a raw pointer or reference (T\* or T&) instead, taken with .get() or \*. Never create two independent shared_ptrs from the same raw pointer, since each creates its own control block and the object is deleted twice. If you need a shared_ptr to 'this', inherit from std::enable_shared_from_this.

The deprecated std::auto_ptr, removed in C++17, had copy syntax that secretly moved; it was the reason unique_ptr and move semantics were created.

## Code examples

### unique_ptr transfers, shared_ptr shares

```
#include <iostream>
#include <memory>
#include <utility>

struct Res {
    Res()  { std::cout << "acquire\n"; }
    ~Res() { std::cout << "release\n"; }
};

std::unique_ptr<Res> make() { return std::make_unique<Res>(); }

int main() {
    auto u = make();
    // auto u2 = u;                    // error: not copyable
    auto u2 = std::move(u);            // ownership transferred
    std::cout << (u ? "u owns" : "u empty") << "\n";

    auto s1 = std::make_shared<int>(10);
    {
        auto s2 = s1;                  // shared ownership
        std::cout << s1.use_count() << "\n";
    }
    std::cout << s1.use_count() << "\n";
}
```

After the move, u is empty. The shared count goes to 2 while s2 lives, then back to 1. u2 releases the Res when main ends.

## Key points

- unique_ptr: exclusive, move-only, zero overhead; make it your default owning pointer.
- shared_ptr: shared ownership via atomic reference counting; costs a control block and atomic operations.
- Prefer make_unique and make_shared: exception safe, one allocation for make_shared, no naked new.
- Never construct two shared_ptrs from the same raw pointer.
- Functions that merely use an object should take T& or T\*, not a smart pointer.

## Common follow-up questions

- Is shared_ptr thread-safe?
- What is enable_shared_from_this used for?
- How would you give a unique_ptr a custom deleter, for example for a FILE\*?

## Interview tips

- Say 'unique_ptr by default, shared_ptr only when ownership is truly shared'.
- Mention the control block to show you know the cost of shared_ptr.

## Concepts covered

unique_ptr, shared_ptr, make_unique, ownership, reference counting

Previous: [Templates and template specialization](https://www.internhack.in/learn/interview/cpp-interview/cpp-templates-specialization) · Next: [weak_ptr and breaking shared_ptr cycles](https://www.internhack.in/learn/interview/cpp-interview/cpp-weak-ptr-circular-references) · [All of C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)

## More C++ & STL questions

- [vector growth and iterator invalidation](https://www.internhack.in/learn/interview/cpp-interview/cpp-vector-growth-iterator-invalidation)
- [map vs unordered_map, and choosing an STL container](https://www.internhack.in/learn/interview/cpp-interview/cpp-map-vs-unordered-map-containers)
- [STL algorithms and priority_queue: sort, lower_bound, heaps](https://www.internhack.in/learn/interview/cpp-interview/cpp-stl-algorithms-priority-queue)
- [Lambdas and capture modes](https://www.internhack.in/learn/interview/cpp-interview/cpp-lambdas-captures)
- [The static keyword and its different meanings](https://www.internhack.in/learn/interview/cpp-interview/cpp-static-keyword)
- [Undefined behaviour: common examples and how to avoid it](https://www.internhack.in/learn/interview/cpp-interview/cpp-undefined-behaviour)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)
