Say Goodbye to Memory Leaks! — Smart Pointers in C++
Memory management in C++ can be tricky. Forget to free memory? Boom! Memory leaks. Free memory twice? Crash! Thankfully, smart pointers help solve these problems by automatically managing memory for you. In this article, we’ll break down smart pointers, explain how they work, and show simple exam...

Say Goodbye to Memory Leaks! — Smart Pointers in C++

Introduction
Memory management in C++ can be tricky. Forget to free memory? Boom! Memory leaks. Free memory twice? Crash! Thankfully, smart pointers help solve these problems by automatically managing memory for you. In this article, we’ll break down smart pointers, explain how they work, and show simple examples to make them easy to understand.
Pre-Request
Before reading further, you should understand that this article assumes you have basic knowledge of:
- Pointers in C++ (“*” and “&” operators).
- Dynamic memory allocation using “new” and “delete”.
- Object-oriented programming concepts like constructors and destructors.
If you’re not familiar with these topics, I recommend reviewing them first to get the most out of this guide. I will surely make another article talking about this concepts. When it’s published, i’ll update this article.
Key Concepts and Terminology
When learning about smart pointers, you may encounter some terms that might not be immediately clear. Here are a few key concepts explained:
Circular Dependency
A circular dependency occurs when two or more objects reference each other in a way that prevents proper memory deallocation. For example, if an object of class “A” holds a shared_ptr to an object of class “B”, and “B” also holds a shared_ptr back to “A”, neither object will ever be destroyed because their reference counts never reach zero. This results in a memory leak.
Solution: Instead of using shared_ptr for both references, one of them should be a weak_ptr, ensuring that the objects do not keep each other alive indefinitely.
Reference Count
The reference count is the number of shared_ptr instances managing the same object. When this count drops to zero, the object is automatically deleted. You can check the reference count of a shared_ptr using .use_count().
Dangling Pointer
A dangling pointer is a pointer that refers to a memory location that has already been deallocated. Accessing a dangling pointer leads to undefined behavior and program crashes. Smart pointers help prevent dangling pointers by ensuring that objects are properly deleted when they are no longer in use.
Ownership Semantics
Ownership semantics define who is responsible for managing an object’s memory.
- unique_ptr enforces exclusive ownership (only one pointer can own an object).
- shared_ptr allows shared ownership (multiple pointers can own an object).
- weak_ptr provides non-owning access (points to an object managed by a shared_ptr but does not affect its lifetime).
By understanding these concepts, you can better utilize smart pointers in C++ and write safer, more efficient code.
What Are Smart Pointers?
A smart pointer is an object that acts like a normal pointer but automatically handles memory allocation and deallocation. This means you don’t have to manually call “delete”, reducing the risk of memory leaks and dangling pointers.
Types of Smart Pointers in C++
C++ provides three types of smart pointers in the <memory> header:
- std::unique_ptr – Owns a resource exclusively.
- std::shared_ptr – Allows multiple smart pointers to share ownership.
- std::weak_ptr – A non-owning reference to a shared_ptr.
But here comes the problem, when to use each of them? So now let’s explore them one by one with examples!
std::unique_ptr — Exclusive Ownership
A unique_ptr owns a resource and cannot be copied. When it goes out of scope, it automatically releases the memory.
Example With Smart Pointer: Managing a Single Object
1#include <iostream>
2#include <memory> //=> This include is required for smart pointers
3
4class Car {
5public:
6 Car() { std::cout << "Car Created\n"; }
7 ~Car() { std::cout << "Car Destroyed\n"; }
8 void drive() { std::cout << "Driving the car!\n"; }
9};
10
11int main() {
12 std::unique_ptr<Car> car = std::make_unique<Car>(); // Create a unique_ptr
13 car->drive(); // Use the object like a normal pointer
14 return 0; // car is automatically deleted here
15}Output
1Car Created
2Driving the car!
3Car DestroyedBut wait, what is the diffrence between this unique_ptr and the normal way of calling a class? Now, let me show you how it’s done on the same class without smart pointer
Example Without Smart Pointer
1#include <iostream>
2
3class Car {
4public:
5 Car() { std::cout << "Car Created\n"; }
6 ~Car() { std::cout << "Car Destroyed\n"; }
7 void drive() { std::cout << "Driving the car!\n"; }
8};
9
10int main() {
11 Car* car = new Car(); // Manually allocate memory
12 car->drive();
13
14 delete car; // Manually free memory (if you forget, it causes a memory leak!)
15 return 0;
16}Output
1Car Created
2Driving the car!
3Car DestroyedNotice that eventho we don’t call delete, the deconstructor is actually being freed. But when we use normal pointer, we should call delete first. Otherwise the memory wouldn’t be freed. The unique_ptr automatically deletes the object when it goes out of scope!
Moving a unique_ptr
Since unique_ptr cannot be copied, you can transfer ownership using std::move().
1std::unique_ptr<Car> car1 = std::make_unique<Car>();
2std::unique_ptr<Car> car2 = std::move(car1); // Ownership moved to car2Now, “car1” is empty, and “car2” owns the object.
std::shared_ptr — Shared Ownership
A shared_ptr allows multiple smart pointers to own the same object. It keeps a reference count, and when the last shared_ptr goes out of scope, the object is deleted.
Example: Multiple Pointers Sharing an Object
1#include <iostream>
2#include <memory>
3
4class Bike {
5public:
6 Bike() { std::cout << "Bike Created\n"; }
7 ~Bike() { std::cout << "Bike Destroyed\n"; }
8 void ride() { std::cout << "Riding the bike!\n"; }
9};
10
11int main() {
12 std::shared_ptr<Bike> bike1 = std::make_shared<Bike>(); // Create shared_ptr
13 {
14 std::shared_ptr<Bike> bike2 = bike1; // Share ownership
15 bike2->ride();
16 std::cout << "Reference Count: " << bike1.use_count() << "\n";
17 } // bike2 goes out of scope, but bike1 still holds ownership
18
19 std::cout << "Reference Count: " << bike1.use_count() << "\n";
20 return 0; // bike1 goes out of scope, object deleted
21}Output
1Bike Created
2Riding the bike!
3Reference Count: 2
4Reference Count: 1
5Bike DestroyedHow It Works:
- “bike1” owns the “Bike” object.
- bike2 = bike1 increases the reference count to 2.
- When “bike2” goes out of scope, the count drops to 1.
- When “bike1” goes out of scope, the count drops to 0, and the object is destroyed.
std::weak_ptr — Avoiding Circular References
A weak_ptr is a non-owning smart pointer that references a shared_ptr without increasing its reference count.
Why Use weak_ptr?
If two objects hold shared_ptr references to each other, they never get deleted due to a circular reference!
Example: Avoiding Circular References
1#include <iostream>
2#include <memory>
3
4class Parent; // Forward declaration
5
6class Child {
7public:
8 std::weak_ptr<Parent> parent; // Weak reference to avoid circular dependency
9 ~Child() { std::cout << "Child Destroyed\n"; }
10};
11
12class Parent {
13public:
14 std::shared_ptr<Child> child;
15 ~Parent() { std::cout << "Parent Destroyed\n"; }
16};
17
18int main() {
19 std::shared_ptr<Parent> p = std::make_shared<Parent>();
20 p->child = std::make_shared<Child>();
21 p->child->parent = p; // Weak pointer prevents circular reference
22}Ouput:
1Child Destroyed
2Parent DestroyedWhen to Use Smart Pointers?
- use unique_ptr when only one object should own the resource
- use shared_ptr when multiple objects share ownership.
- use weak_ptr when avoiding circular dependencies with shared_ptr.
Final Thoughts
Smart pointers are a powerful tool in C++ that make memory management safe and automatic. By using unique_ptr, shared_ptr, and weak_ptr correctly, you can avoid memory leaks and dangling pointers.
Next time you write C++ code, consider using smart pointers instead of raw pointers. Your future self will thank you!
Originally published on Medium: https://medium.com/@danendraclever24/say-goodbye-to-memory-leaks-smart-pointers-in-c-6ca29047d00f