Smart Pointers in Depth

📘 C++ 👁 30 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Smart pointers are objects that manage dynamic memory automatically, ensuring proper resource release and preventing memory leaks.

They are defined in the header:

#include

Why Smart Pointers?

Problems with raw pointers:

  • Memory leaks

  • Dangling pointers

  • Double deletion

Smart pointers solve these using RAII (Resource Acquisition Is Initialization).


Types of Smart Pointers

C++ provides three main smart pointers:

  1. unique_ptr

  2. shared_ptr

  3. weak_ptr


1. unique_ptr

Description

  • Owns the memory exclusively

  • Cannot be copied

  • Can be moved

Syntax

unique_ptr<int> ptr = make_unique<int>(10);

Example

#include #include using namespace std; int main() { unique_ptr<int> p = make_unique<int>(5); cout << *p; return 0; }

Key Features

  • Lightweight

  • Fast

  • Automatically deletes memory

Move Ownership

unique_ptr<int> p1 = make_unique<int>(10); unique_ptr<int> p2 = move(p1);

2. shared_ptr

Description

  • Multiple pointers share ownership

  • Uses reference counting

  • Memory freed when count becomes zero

Syntax

shared_ptr<int> ptr = make_shared<int>(20);

Example

shared_ptr<int> p1 = make_shared<int>(30); shared_ptr<int> p2 = p1; cout << p>1.use_count(); // Output: 2

Key Features

  • Safe shared ownership

  • Slight overhead due to reference counting


3. weak_ptr

Description

  • Does not own the object

  • Prevents circular references

  • Used with shared_ptr

Syntax

weak_ptr<int> wp;

Example

shared_ptr<int> sp = make_shared<int>(40); weak_ptr<int> wp = sp; if (auto temp = wp.lock()) { cout << *temp; }

Comparison of Smart Pointers

Featureunique_ptrshared_ptrweak_ptr
OwnershipSingleMultipleNone
CopyableNoYesYes
Reference countNoYesNo
Memory overheadLowMediumLow
Use caseExclusive ownershipShared resourcesBreaking cycles

Custom Deleters

Used when memory needs special cleanup.

unique_ptrdecltype(&fclose)> fp(fopen("file.txt","r"), &fclose);

Smart Pointers vs Raw Pointers

Raw PointerSmart Pointer
Manual memory controlAutomatic memory control
Error-proneSafe
No ownership conceptClear ownership

Best Practices

  • Prefer make_unique and make_shared

  • Use unique_ptr by default

  • Use shared_ptr only when sharing is required

  • Use weak_ptr to avoid circular dependencies

  • Avoid mixing raw and smart pointers


Key Points

  • Smart pointers follow RAII

  • Prevent memory leaks

  • Improve code safety and clarity

  • Essential in modern C++


Conclusion

Smart pointers are a core feature of modern C++ that provide safe, automatic, and efficient memory management.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes