🧠 Smart Pointers in C++ – unique_ptr
and shared_ptr
Smart pointers are part of the C++11 standard and help manage dynamic memory safely and efficiently. They automatically deallocate memory when it is no longer needed, reducing the chances of memory leaks and dangling pointers.
📘 What Are Smart Pointers?
Smart pointers are template classes provided in the <memory>
header that manage ownership of a dynamically allocated object.
unique_ptr
– Single owner of the memoryshared_ptr
– Shared ownership (reference counted)
💡 Benefits of Smart Pointers
- Automatic memory management
- Prevents memory leaks
- Safer than raw pointers
- Supports RAII (Resource Acquisition Is Initialization)
💻 Example: Using unique_ptr
and shared_ptr
#include <iostream>
#include <memory>
using namespace std;
class Demo {
public:
Demo() { cout << "Constructor Called\\n"; }
~Demo() { cout << "Destructor Called\\n"; }
void display() { cout << "Inside display()\\n"; }
};
int main() {
// unique_ptr example
unique_ptr<Demo> ptr1 = make_unique<Demo>();
ptr1->display();
// shared_ptr example
shared_ptr<Demo> ptr2 = make_shared<Demo>();
shared_ptr<Demo> ptr3 = ptr2; // shared ownership
cout << "Reference count: " << ptr2.use_count() << endl;
ptr2->display();
ptr3->display();
return 0;
}
📝 Sample Output
Constructor Called
Inside display()
Constructor Called
Reference count: 2
Inside display()
Inside display()
Destructor Called
Destructor Called
Inside display()
Constructor Called
Reference count: 2
Inside display()
Inside display()
Destructor Called
Destructor Called
🔍 Explanation
unique_ptr
cannot be copied—only moved. It ensures single ownership.shared_ptr
maintains a reference count. All references are deleted when the count becomes zero.- Both smart pointers automatically destroy the object when it goes out of scope.
📌 When to Use?
- Use
unique_ptr
when you want exclusive ownership. - Use
shared_ptr
when multiple objects share ownership of a resource.
Post a Comment