Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
822 lines (658 loc) · 18.5 KB

File metadata and controls

822 lines (658 loc) · 18.5 KB

🚀 C++ Smart Pointers: Complete Guide

📚 Overview

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.

🎯 Key Concepts

What are Smart Pointers?

  • 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

Types of Smart Pointers

  • 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

🔒 Unique Pointer (unique_ptr)

Basic Usage

#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;
}

Unique Pointer with Custom Deleter

#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;
}

Unique Pointer in Functions

#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;
}

Unique Pointer in Containers

#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;
}

🔗 Shared Pointer (shared_ptr)

Basic Usage

#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;
}

Shared Pointer with Custom Deleter

#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;
}

Shared Pointer and Inheritance

#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;
}

Shared Pointer in Data Structures

#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;
}

🔗 Weak Pointer (weak_ptr)

Basic Usage

#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;
}

Weak Pointer to Break Circular References

#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;
}

🚀 Advanced Smart Pointer Features

Enable Shared From This

#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;
}

Smart Pointer Arrays

#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;
}

Smart Pointer with Polymorphic Deleter

#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;
}

📝 Best Practices

1. Prefer make_unique and make_shared

// 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"));

2. Use unique_ptr by Default

// 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>();

3. Avoid Circular References

// 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
};

4. Don't Use get() Unless Necessary

// 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 needed

5. Use weak_ptr for Observers

classSubject {
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();
}
}
}
};

🎯 Performance Considerations

Shared Pointer Overhead

#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;
}

Memory Layout

// 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*)

🎯 Practice Problems

Problem 1: Resource Manager

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();
}
};

Problem 2: Observer Pattern

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);
}
}
}
};

Problem 3: Factory Pattern

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;
}
};

📚 Summary

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!


🔗 Related Topics