C++ Day 33: Smart Pointers & Memory Management
๐น 1. wherefore forward pointers
in c++ hand-operated green / cancel is error-prone:
memory leaks ๐ง
double deletes ❌
dangling pointers ๐ฅ
smart pointers care store mechanically exploitation raii (Supply skill is initialization)
๐น ii. Types of Smart Pointers in C++
✅ std::unique_ptr
Sole ownership of a Supply.
Cannot be copied.
Automatically deletes the Supply when it goes out of scope.
cpp
Copy
Edit
#include
unique_ptr ptr1 = make_unique(10);
cout << *ptr1 << endl; // 10
You can transfer ownership:
cpp
Copy
Edit
unique_ptr ptr2 = move(ptr1);
✅ std::shared_ptr
Shared ownership multiple shared_ptrs can point to the same object.
Uses reference counting to track how many owners.
cpp
Copy
Edit
shared_ptr p1 = make_shared(100);
shared_ptr p2 = p1; // Reference count = 2
When count goes to 0 memory is released.
✅ std::weak_ptr
Non-owning reference to a shared_ptr-managed object.
Used to break cyclic references (e.g. in graphs or linked structures).
cpp
Copy
Edit
shared_ptr sp = make_shared(50);
weak_ptr wp = sp;
if (auto temp = wp.lock()) {
cout << *temp << endl;
}
๐น 3. bespoke deleters
you get delineate however amp forward arrow need cancel its object
cpp
copy
edit
unique_ptr file(fopen("Checktxt" "r") &fclose);
๐น cardinal. Common Mistakes
Using raw pointers where smart pointers are better.
Creating cyclic references with shared_ptr.
Forgetting move() with unique_ptr.
๐น 5. compare table
Characteristic unique_ptr shared_ptr weak_ptr
ownership exclusive shared non-owning
copyable ❌ ✅ ✅
reference cnt ❌ ✅ ✅ (uses weak)
use case single owner multiple use avoid cycles
๐งช do task:
Make amp family hold and care amp active range of hold objects exploitation shared_ptr. Add a method to show the reference count of a particular Book.
✅ Summary:
Smart pointers = safer dynamic memory
Use make_unique / make_shared instead of new
Prefer unique_ptr by default shared_ptr when needed
Comments
Post a Comment