Smart Pointers

unique_ptr, shared_ptr, weak_ptr

Interview Relevant: Modern C++ essential

Smart Pointers

RAII wrappers that automatically manage memory (C++11).

Code Examples

Smart pointers for automatic memory management.

cpp
1#include <memory>
2
3// unique_ptr - exclusive ownership
4auto p1 = make_unique<int>(42);
5cout << *p1;  // 42
6// unique_ptr<int> p2 = p1;  // Error! Can't copy
7auto p2 = move(p1);  // Transfer ownership
8
9// shared_ptr - shared ownership
10auto sp1 = make_shared<int>(10);
11auto sp2 = sp1;  // Both own the object
12cout << sp1.use_count();  // 2
13sp1.reset();  // Release sp1's ownership
14cout << sp2.use_count();  // 1
15
16// weak_ptr - non-owning observer
17weak_ptr<int> wp = sp2;
18if (auto locked = wp.lock()) {  // Get shared_ptr
19    cout << *locked;
20}
21
22// Custom deleter
23auto filePtr = unique_ptr<FILE, decltype(&fclose)>(
24    fopen("file.txt", "r"), fclose);
25
26// Smart pointer to array
27auto arr = make_unique<int[]>(10);

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In