Smart pointers are C++ objects that manage the lifetime of dynamically allocated memory automatically. They provide automatic memory management, preventing memory leaks and dangling pointers, while maintaining RAII (Resource Acquisition Is Initialization) principles.
- Automatic memory management: Memory is automatically freed when no longer needed
- RAII compliance: Resources are managed through object lifetime
- Exception safety: Memory is freed even when exceptions occur
- No manual delete: Eliminates the need for manual memory deallocation
- unique_ptr: Exclusive ownership, move-only
- shared_ptr: Shared ownership with reference counting
- weak_ptr: Non-owning reference to shared_ptr
- auto_ptr: Deprecated (C++17), replaced by unique_ptr
#include<memory>
#include<iostream>usingnamespacestd;intmain() {
// Create unique_ptr
unique_ptr<int> ptr1(newint(42));
unique_ptr<int> ptr2 = make_unique<int>(100); // Preferred way// Access the value
cout << "Value: " << *ptr1 << endl;
cout << "Value: " << *ptr2 << endl;
// Check if pointer is validif (ptr1) {
cout << "ptr1 is valid" << endl;
}
// Reset pointer
ptr1.reset(); // ptr1 now points to nullptrif (!ptr1) {
cout << "ptr1 is now null" << endl;
}
// Release ownershipint* rawPtr = ptr2.release(); // ptr2 now owns nothing
cout << "Raw pointer value: " << *rawPtr << endl;
delete rawPtr; // Manual cleanup requiredreturn0;
}#include<memory>
#include<iostream>
#include<cstdio>usingnamespacestd;// Custom deleter for FILE*structFileDeleter {
voidoperator()(FILE* file) {
if (file) {
fclose(file);
cout << "File closed" << endl;
}
}
};
// Custom deleter for arraysstructArrayDeleter {
voidoperator()(int* ptr) {
delete[] ptr;
cout << "Array deleted" << endl;
}
};
intmain() {
// unique_ptr with custom deleter
unique_ptr<FILE, FileDeleter> filePtr(fopen("test.txt", "w"));
if (filePtr) {
fprintf(filePtr.get(), "Hello, World!");
}
// unique_ptr for arrays
unique_ptr<int, ArrayDeleter> arrayPtr(newint[5]{1, 2, 3, 4, 5});
// Lambda deleterauto lambdaDeleter = [](int* ptr) {
delete ptr;
cout << "Lambda deleter called" << endl;
};
unique_ptr<int, decltype(lambdaDeleter)> lambdaPtr(newint(42), lambdaDeleter);
return0;
}#include<memory>
#include<iostream>usingnamespacestd;// Function that takes ownershipvoidtakeOwnership(unique_ptr<int> ptr) {
cout << "Ownership transferred, value: " << *ptr << endl;
// ptr is automatically deleted when function ends
}
// Function that returns unique_ptr
unique_ptr<int> createValue(int value) {
return make_unique<int>(value);
}
// Function that conditionally returns unique_ptr
unique_ptr<int> maybeCreateValue(bool shouldCreate) {
if (shouldCreate) {
return make_unique<int>(42);
}
returnnullptr;
}
intmain() {
auto ptr1 = make_unique<int>(100);
// Transfer ownership to functiontakeOwnership(move(ptr1)); // ptr1 is now nullptr// Get unique_ptr from functionauto ptr2 = createValue(200);
cout << "Received value: " << *ptr2 << endl;
// Conditional creationauto ptr3 = maybeCreateValue(true);
if (ptr3) {
cout << "Created value: " << *ptr3 << endl;
}
return0;
}#include<memory>
#include<vector>
#include<iostream>usingnamespacestd;intmain() {
// Vector of unique_ptr
vector<unique_ptr<int>> numbers;
// Add elements
numbers.push_back(make_unique<int>(1));
numbers.push_back(make_unique<int>(2));
numbers.push_back(make_unique<int>(3));
// Access elementsfor (constauto& ptr : numbers) {
cout << *ptr << "";
}
cout << endl;
// Cannot copy unique_ptr, but can move
vector<unique_ptr<int>> numbers2;
for (auto& ptr : numbers) {
numbers2.push_back(move(ptr));
}
// numbers now contains nullptr pointers// numbers2 owns the actual integersreturn0;
}#include<memory>
#include<iostream>usingnamespacestd;classResource {
public:Resource(int value) : data(value) {
cout << "Resource " << data << " created" << endl;
}
~Resource() {
cout << "Resource " << data << " destroyed" << endl;
}
intgetValue() const { return data; }
private:int data;
};
intmain() {
// Create shared_ptr
shared_ptr<Resource> ptr1 = make_shared<Resource>(42);
shared_ptr<Resource> ptr2 = ptr1; // Reference count: 2
cout << "Reference count: " << ptr1.use_count() << endl;
// Access the resource
cout << "Value: " << ptr1->getValue() << endl;
cout << "Value: " << ptr2->getValue() << endl;
// Reset one pointer
ptr1.reset(); // Reference count: 1
cout << "After reset, reference count: " << ptr2.use_count() << endl;
// Reset the other pointer
ptr2.reset(); // Reference count: 0, Resource destroyedreturn0;
}#include<memory>
#include<iostream>usingnamespacestd;// Custom deleter functionvoidcustomDelete(int* ptr) {
cout << "Custom delete called for value: " << *ptr << endl;
delete ptr;
}
// Custom deleter classstructCustomDeleter {
voidoperator()(int* ptr) {
cout << "Custom deleter operator called for value: " << *ptr << endl;
delete ptr;
}
};
intmain() {
// Function pointer deleter
shared_ptr<int> ptr1(newint(42), customDelete);
// Function object deleter
shared_ptr<int> ptr2(newint(100), CustomDeleter{});
// Lambda deleterauto lambdaDeleter = [](int* ptr) {
cout << "Lambda deleter called for value: " << *ptr << endl;
delete ptr;
};
shared_ptr<int> ptr3(newint(200), lambdaDeleter);
return0;
}#include<memory>
#include<iostream>usingnamespacestd;classBase {
public:virtual~Base() {
cout << "Base destructor" << endl;
}
virtualvoiddisplay() const {
cout << "Base class" << endl;
}
};
classDerived : publicBase {
public:~Derived() override {
cout << "Derived destructor" << endl;
}
voiddisplay() constoverride {
cout << "Derived class" << endl;
}
};
intmain() {
// Create shared_ptr to derived class
shared_ptr<Derived> derivedPtr = make_shared<Derived>();
// Assign to base class pointer (polymorphism)
shared_ptr<Base> basePtr = derivedPtr;
// Both pointers share ownership
cout << "Reference count: " << derivedPtr.use_count() << endl;
cout << "Reference count: " << basePtr.use_count() << endl;
// Polymorphic behavior
basePtr->display();
derivedPtr->display();
return0;
}#include<memory>
#include<iostream>usingnamespacestd;structNode {
int data;
shared_ptr<Node> next;
Node(int value) : data(value), next(nullptr) {}
};
classLinkedList {
private:
shared_ptr<Node> head;
public:voidinsert(int value) {
auto newNode = make_shared<Node>(value);
newNode->next = head;
head = newNode;
}
voiddisplay() const {
auto current = head;
while (current) {
cout << current->data << "";
current = current->next;
}
cout << endl;
}
// Note: This can cause stack overflow for long lists// due to recursive destruction of shared_ptr
};
intmain() {
LinkedList list;
list.insert(3);
list.insert(2);
list.insert(1);
list.display();
return0;
}#include<memory>
#include<iostream>usingnamespacestd;intmain() {
shared_ptr<int> sharedPtr = make_shared<int>(42);
// Create weak_ptr from shared_ptr
weak_ptr<int> weakPtr = sharedPtr;
// Check if weak_ptr is validif (auto lockedPtr = weakPtr.lock()) {
cout << "Weak pointer is valid, value: " << *lockedPtr << endl;
} else {
cout << "Weak pointer is expired" << endl;
}
// Check use count
cout << "Shared pointer use count: " << sharedPtr.use_count() << endl;
// Reset shared_ptr
sharedPtr.reset();
// Check weak_ptr againif (auto lockedPtr = weakPtr.lock()) {
cout << "Weak pointer is still valid" << endl;
} else {
cout << "Weak pointer is now expired" << endl;
}
return0;
}#include<memory>
#include<iostream>usingnamespacestd;structNode {
int data;
shared_ptr<Node> next;
weak_ptr<Node> prev; // Use weak_ptr to break circular referenceNode(int value) : data(value), next(nullptr) {}
};
classCircularList {
private:
shared_ptr<Node> head;
public:voidinsert(int value) {
auto newNode = make_shared<Node>(value);
if (!head) {
head = newNode;
newNode->next = head;
newNode->prev = head;
} else {
newNode->next = head;
newNode->prev = head->prev;
if (auto prevNode = head->prev.lock()) {
prevNode->next = newNode;
}
head->prev = newNode;
}
}
voiddisplay() const {
if (!head) return;
auto current = head;
do {
cout << current->data << "";
current = current->next;
} while (current != head);
cout << endl;
}
};
intmain() {
CircularList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.display();
return0;
}#include<memory>
#include<iostream>usingnamespacestd;classWidget : publicenable_shared_from_this<Widget> {
public:Widget() {
cout << "Widget created" << endl;
}
~Widget() {
cout << "Widget destroyed" << endl;
}
shared_ptr<Widget> getShared() {
returnshared_from_this();
}
voidprocess() {
cout << "Processing widget" << endl;
}
};
intmain() {
auto widget = make_shared<Widget>();
// Get shared_ptr from thisauto sharedWidget = widget->getShared();
cout << "Reference count: " << widget.use_count() << endl;
return0;
}#include<memory>
#include<iostream>usingnamespacestd;intmain() {
// C++11: unique_ptr for arrays
unique_ptr<int[]> array1(newint[5]{1, 2, 3, 4, 5});
// Access elementsfor (int i = 0; i < 5; i++) {
cout << array1[i] << "";
}
cout << endl;
// C++17: shared_ptr for arrays
shared_ptr<int[]> array2 = make_shared<int[]>(5);
for (int i = 0; i < 5; i++) {
array2[i] = i + 1;
}
// C++20: make_unique for arraysauto array3 = make_unique<int[]>(5);
for (int i = 0; i < 5; i++) {
array3[i] = i + 1;
}
return0;
}#include<memory>
#include<iostream>usingnamespacestd;// Base class for different resource typesclassResource {
public:virtual~Resource() = default;
virtualvoidcleanup() = 0;
};
classFileResource : publicResource {
public:voidcleanup() override {
cout << "File resource cleaned up" << endl;
}
};
classNetworkResource : publicResource {
public:voidcleanup() override {
cout << "Network resource cleaned up" << endl;
}
};
// Polymorphic deleterstructPolymorphicDeleter {
voidoperator()(Resource* ptr) {
if (ptr) {
ptr->cleanup();
delete ptr;
}
}
};
intmain() {
// Create unique_ptr with polymorphic deleter
unique_ptr<Resource, PolymorphicDeleter> filePtr(newFileResource());
unique_ptr<Resource, PolymorphicDeleter> networkPtr(newNetworkResource());
return0;
}// Good: Use make functionsauto ptr1 = make_unique<int>(42);
auto ptr2 = make_shared<string>("Hello");
// Bad: Direct construction
unique_ptr<int> ptr3(newint(42));
shared_ptr<string> ptr4(new string("Hello"));// Good: Use unique_ptr when you need exclusive ownership
unique_ptr<Resource> resource = make_unique<Resource>();
// Only use shared_ptr when you need shared ownership
shared_ptr<Resource> sharedResource = make_shared<Resource>();// Bad: Circular reference with shared_ptrstructBadNode {
shared_ptr<BadNode> next;
shared_ptr<BadNode> prev; // Circular reference!
};
// Good: Use weak_ptr to break circular referencesstructGoodNode {
shared_ptr<GoodNode> next;
weak_ptr<GoodNode> prev; // No circular reference
};// Bad: Using get() unnecessarilyauto ptr = make_unique<int>(42);
int* rawPtr = ptr.get();
delete rawPtr; // Double deletion!// Good: Let smart pointer manage memoryauto ptr = make_unique<int>(42);
// No manual deletion neededclassSubject {
private:
vector<weak_ptr<Observer>> observers;
public:voidaddObserver(weak_ptr<Observer> observer) {
observers.push_back(observer);
}
voidnotify() {
// Remove expired observers
observers.erase(
remove_if(observers.begin(), observers.end(),
[](const weak_ptr<Observer>& wp) { return wp.expired(); }),
observers.end()
);
// Notify valid observersfor (auto& observer : observers) {
if (auto obs = observer.lock()) {
obs->update();
}
}
}
};#include<memory>
#include<chrono>
#include<vector>voidbenchmark() {
constint iterations = 1000000;
// unique_ptr performanceauto start = chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; i++) {
auto ptr = make_unique<int>(i);
}
auto end = chrono::high_resolution_clock::now();
auto unique_time = chrono::duration_cast<chrono::microseconds>(end - start);
// shared_ptr performance
start = chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; i++) {
auto ptr = make_shared<int>(i);
}
end = chrono::high_resolution_clock::now();
auto shared_time = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "unique_ptr time: " << unique_time.count() << " μs" << endl;
cout << "shared_ptr time: " << shared_time.count() << " μs" << endl;
}// unique_ptr: Single pointer, no overhead
unique_ptr<int> ptr; // Size: sizeof(int*)// shared_ptr: Two pointers (object + control block)
shared_ptr<int> ptr; // Size: 2 * sizeof(int*)// weak_ptr: Two pointers (same as shared_ptr)
weak_ptr<int> ptr; // Size: 2 * sizeof(int*)classResourceManager {
private:
unique_ptr<Resource> resource;
public:ResourceManager() = default;
voidsetResource(unique_ptr<Resource> newResource) {
resource = move(newResource);
}
Resource* getResource() const {
return resource.get();
}
boolhasResource() const {
return resource != nullptr;
}
voidclearResource() {
resource.reset();
}
};classObserver {
public:virtual~Observer() = default;
virtualvoidupdate(const string& message) = 0;
};
classSubject {
private:
vector<weak_ptr<Observer>> observers;
public:voidaddObserver(weak_ptr<Observer> observer) {
observers.push_back(observer);
}
voidnotify(const string& message) {
// Remove expired observers
observers.erase(
remove_if(observers.begin(), observers.end(),
[](const weak_ptr<Observer>& wp) { return wp.expired(); }),
observers.end()
);
// Notify valid observersfor (auto& observer : observers) {
if (auto obs = observer.lock()) {
obs->update(message);
}
}
}
};classProduct {
public:virtual~Product() = default;
virtualvoidoperation() = 0;
};
classConcreteProductA : publicProduct {
public:voidoperation() override {
cout << "ConcreteProductA operation" << endl;
}
};
classConcreteProductB : publicProduct {
public:voidoperation() override {
cout << "ConcreteProductB operation" << endl;
}
};
classFactory {
public:static unique_ptr<Product> createProduct(const string& type) {
if (type == "A") {
return make_unique<ConcreteProductA>();
} elseif (type == "B") {
return make_unique<ConcreteProductB>();
}
returnnullptr;
}
};Key takeaways:
- Use smart pointers instead of raw pointers for automatic memory management
- Prefer unique_ptr for exclusive ownership and shared_ptr for shared ownership
- Use weak_ptr to break circular references and implement observer patterns
- Use make_unique and make_shared for exception-safe creation
- Understand the performance implications of different smart pointer types
- Follow RAII principles for resource management
- Avoid common pitfalls like circular references and unnecessary get() usage
Master smart pointers to write safe, modern C++ code with automatic memory management!