Skip to main content
eLearner.app
Module 7 · Lesson 1 of 215/18 in the course~12 min
Module lessons (1/2)

std::unique_ptr and std::shared_ptr

In classical C++, manual memory management using the new and delete operators is a common source of bugs such as memory leaks (resources never released) or dangling pointers (pointers pointing to deallocated memory).

Modern C++ introduces Smart Pointers, defined in the <memory> header. They automatically manage the lifecycle of heap-allocated memory using RAII (Resource Acquisition Is Initialization), deallocating the resource when the smart pointer goes out of scope.

std::unique_ptr

std::unique_ptr implements the concept of exclusive ownership of a resource. It cannot be copied, only moved (via std::move).

Code
#include <memory>

// Recommended creation using std::make_unique (C++14)
std::unique_ptr<int> p1 = std::make_unique<int>(42);

// Accessing the resource like a normal pointer
std::cout << *p1 << std::endl;

// std::unique_ptr<int> p2 = p1; // COMPILER ERROR: copy not allowed!
std::unique_ptr<int> p2 = std::move(p1); // Allowed: p1 transfers ownership to p2

std::shared_ptr

std::shared_ptr implements the concept of shared ownership. Multiple smart pointers can point to the same resource. The class internally maintains a reference count: the memory is freed only when the last active shared_ptr is destroyed or reset.

Code
#include <memory>

std::shared_ptr<int> s1 = std::make_shared<int>(100);
std::shared_ptr<int> s2 = s1; // Allowed: increments the reference count

std::cout << s1.use_count() << std::endl; // Prints 2 (s1 and s2 share the resource)

Try it yourself

Exercise#cpp.m7.l1.e1
Attempts: 0Loading…

Declare a std::unique_ptr<int> named ptr, initializing it with std::make_unique holding the value 42. Print the dereferenced value of ptr using std::cout.

Loading editor…
Show hint

Use `std::unique_ptr<int> ptr = std::make_unique<int>(42);` and then send `*ptr` to the output stream.

Solution available after 3 attempts

Exercise#cpp.m7.l1.e2
Attempts: 0Loading…

Instantiate a std::shared_ptr<int> named ptr1 with the value 100 using std::make_shared. Create a copy named ptr2, and print the value returned by ptr1.use_count() using std::cout.

Loading editor…
Show hint

Copying is done via standard assignment: `ptr2 = ptr1;`. Printing `ptr1.use_count()` should display 2.

Solution available after 3 attempts