Introduced in C++11, smart pointers are modern tools that simplify memory management and eliminate the need to manually call delete. Smart pointers automatically manage the lifetime of dynamically allocated objects and significantly reduce memory leaks. In this article, we examine the three main types of smart pointers: unique_ptr, shared_ptr, and weak_ptr.


1) What Is a Smart Pointer?

A smart pointer is a special class that behaves like a pointer but automatically releases memory when it is no longer needed. Smart pointers typically follow the RAII (Resource Acquisition Is Initialization) principle.

Advantages:

  • Prevents memory leaks
  • Controls object ownership
  • No need to call delete manually
  • Essential in modern, safe C++ programming

2) unique_ptr

unique_ptr allows an object to have only one owner. No other unique_ptr can own the same object.

Basic usage:


#include <memory>

int main() {
    unique_ptr<int> p = make_unique<int>(10);
    cout << *p << endl;
}

Transferring ownership (move):


unique_ptr<int> p1 = make_unique<int>(20);
unique_ptr<int> p2 = std::move(p1); // ownership transferred to p2

Note: A unique_ptr cannot be copied — it can only be moved.


3) shared_ptr

shared_ptr allows multiple owners for the same object. It keeps track of ownership using a reference count.

Example:


#include <memory>

int main() {
    shared_ptr<string> p1 = make_shared<string>("Hello");
    shared_ptr<string> p2 = p1; // reference count becomes 2

    cout << *p1 << endl;
    cout << "Owner count: " << p2.use_count();
}

The object's memory is automatically released when the reference count reaches zero.


4) weak_ptr

weak_ptr references an object managed by shared_ptr without taking ownership. It is essential for preventing cyclic reference issues.

Example:


#include <memory>

int main() {
    shared_ptr<int> sp = make_shared<int>(50);
    weak_ptr<int> wp = sp; // observing without owning

    if (auto locked = wp.lock()) {
        cout << *locked;
    }
}

weak_ptr cannot access the object directly; it must use lock() to obtain a temporary shared_ptr.


5) unique_ptr vs shared_ptr vs weak_ptr

Type Description Ownership
unique_ptr Single ownership, cannot be copied 1
shared_ptr Shared ownership with reference counting N
weak_ptr Non-owning observer of a shared_ptr 0

6) Tips for Using Smart Pointers

  • Prefer unique_ptr by default
  • Use shared_ptr only when multiple owners are required
  • Use weak_ptr to break circular ownership
  • Prefer make_unique and make_shared over raw allocations
  • Avoid calling delete — smart pointers handle it automatically

7) TL;DR

  • unique_ptr → single ownership, movable
  • shared_ptr → shared ownership, reference counting
  • weak_ptr → observes shared_ptr without owning it
  • Smart pointers greatly improve memory safety
  • All examples work with Visual Studio 2022, GCC, and Clang