Topic 78 of 83
Smart Pointers
Overview
Smart Pointers (C++11) are classes that wrap raw pointers. They automatically manage memory (RAII) and `delete` the memory when the pointer goes out of scope, eliminating memory leaks.
Syntax
cpp
#include <memory>
// unique_ptr: Exclusive ownership. Cannot be copied, only moved.
std::unique_ptr<int> uptr = std::make_unique<int>(100);
// shared_ptr: Shared ownership. Keeps a reference count.
std::shared_ptr<int> sptr1 = std::make_shared<int>(200);
std::shared_ptr<int> sptr2 = sptr1; // Count is now 2
// weak_ptr: Observes a shared_ptr without increasing the count.
std::weak_ptr<int> wptr = sptr1;Common Pitfalls
- Trying to copy a `unique_ptr` by value (e.g., passing it to a function without `std::move`). The compiler will instantly throw an error.
Interview Tips
- Always prefer `std::make_unique` and `std::make_shared` over using `new`. They are safer (exception-safe) and faster.
- Be prepared to explain 'Circular References' with shared_ptrs and how weak_ptrs solve them by not incrementing the reference count.
Real-World Example
Safe memory management that automatically cleans up.
example
cpp
#include <iostream>
#include <memory>
using namespace std;
class Entity {
public:
Entity() { cout << "Created\n"; }
~Entity() { cout << "Destroyed\n"; }
};
int main() {
{
// Allocate in this scope
unique_ptr<Entity> e = make_unique<Entity>();
} // e goes out of scope here. Automatically destroyed!
cout << "End of main\n";
return 0;
}