βš™οΈ C++ Advanced Concepts
Estimated reading: 3 minutes 24 views

🧠 C++ Smart Pointers – Modern Memory Management Made Easy


🧲 Introduction – What Are Smart Pointers in C++?

Smart pointers in C++ are template-based classes that automatically manage dynamically allocated memory. Introduced in C++11, smart pointers eliminate the need to explicitly use delete, thereby reducing the risk of memory leaks, dangling pointers, and undefined behavior.

🎯 In this section, you’ll understand:

  • Types of smart pointers: unique_ptr, shared_ptr, weak_ptr
  • Ownership models and when to use each
  • Common pitfalls and safe usage practices

πŸ” Why Use Smart Pointers?

Traditional memory management using new and delete is manual and error-prone. Smart pointers:

  • Automatically free memory when no longer needed
  • Prevent double deletion and dangling pointers
  • Simplify exception-safe code

πŸ’‘ Types of Smart Pointers

Smart PointerDescriptionUse Case
std::unique_ptrOwns an object exclusively (no copies allowed)Resource with a single owner
std::shared_ptrShared ownership via reference countingMultiple owners needing shared access
std::weak_ptrObserves shared_ptr without affecting ref countBreak cyclic dependencies in shared_ptr

πŸ’» Code Examples

βœ… std::unique_ptr Example

#include <iostream>
#include <memory>
using namespace std;

int main() {
    unique_ptr<int> ptr = make_unique<int>(10);
    cout << *ptr << endl;  // Output: 10
    return 0;
}

βœ… std::shared_ptr Example

shared_ptr<int> p1 = make_shared<int>(100);
shared_ptr<int> p2 = p1;  // Reference count increases
cout << *p2 << endl;

βœ… std::weak_ptr Example

shared_ptr<int> sp = make_shared<int>(42);
weak_ptr<int> wp = sp;  // No ownership
if (auto temp = wp.lock()) {
    cout << *temp << endl;
}

🧱 Ownership and Lifetime

  • unique_ptr cannot be copied, only moved (std::move)
  • shared_ptr maintains a reference count; object is destroyed when count is 0
  • weak_ptr is used to observe shared_ptr without increasing its reference count

πŸ“˜ Best Practices

πŸ“˜ Use make_unique<T>() and make_shared<T>() to construct smart pointers
πŸ“¦ Don’t mix raw pointers with smart pointers
πŸ” Use weak_ptr in graph/linked data structures to avoid cyclic references
πŸ›‘ Always prefer unique_ptr unless you need sharing


⚠️ Common Mistakes to Avoid

  • Forgetting to use delete[] for arrays (not needed with smart pointers)
  • Using raw new/delete alongside smart pointers
  • Using shared_ptr when unique_ptr suffices (performance penalty)

πŸ“Œ Summary

  • Smart pointers manage memory automatically and safely
  • Use unique_ptr for single ownership, shared_ptr for shared, and weak_ptr to avoid cycles
  • Replaces raw new/delete for modern C++ memory management

❓FAQ

❓ Why use smart pointers instead of raw pointers?
They automatically deallocate memory, preventing leaks and errors.

❓ Can I copy a unique_ptr?
No. You must use std::move() to transfer ownership.

❓ What is the overhead of shared_ptr?
Slightly more than unique_ptr due to reference counting.

❓ Do smart pointers work with arrays?
Yes, unique_ptr<T[]> can be used for arrays.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

C++ Smart Pointers

Or Copy Link

CONTENTS
Scroll to Top