Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Modern C++: Smart Pointers in Depth

Lesson 52 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Ending the Nightmare of Memory Leaks

In old C++, if you called new, you had to call delete. If you forgot, your program leaked memory. In Modern C++ (C++11 and later), we use Smart Pointers to handle this automatically.

1. std::unique_ptr

Represents exclusive ownership.

  • Only one unique_ptr can point to a memory block at a time.
  • When the pointer goes out of scope, it automatically deletes the memory.
  • You cannot copy it, but you can "move" it to another unique_ptr.

2. std::shared_ptr

Represents shared ownership.

  • Multiple pointers can point to the same memory.
  • It keeps a "Reference Count" (a count of how many pointers are looking at it).
  • The memory is only deleted when the last shared_ptr is destroyed.

3. std::weak_ptr

A "companion" to shared_ptr.

  • It looks at the memory but doesn't increase the reference count.
  • Used to prevent "Circular Dependencies" (where two objects point to each other and never get deleted).

Why use them?

  • Safety: No more delete means no more forgetting to free memory.
  • Exceptions: If an error happens and the program jumps away, smart pointers still clean up themselves.
  • Clarity: It's obvious who "owns" the data.
In modern C++, you should almost never use the new and delete keywords. Use std::make_unique and std::make_shared instead!