Basic Usage of Smart Pointers
Smart Pointer Overview
A smart pointer is a class template that wraps a raw pointer and automatically releases the pointed-to resource upon destruction. Common smart pointers include std::unique_ptr, std::shared_ptr, and std::weak_ptr.
std::unique_ptr
std::unique_ptr is an exclusive ownership smart pointer that ensures only one unique_ptr object owns the resource at any time.
Creating std::unique_ptr
#include <memory>
#include <iostream>
int main() {
// Create a unique_ptr managing an int object
std::unique_ptr<int> ptr(new int(42));
// Access the pointed-to object
std::cout << *ptr << std::endl;
// unique_ptr automatically releases the resource when leaving scope
return 0;
}
Move Semantics
std::unique_ptr supports move semantics, allowing ownership transfer from one unique_ptr to another.
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> ptr1(new int(42));
std::unique_ptr<int> ptr2 = std::move(ptr1); // Move ownership
// ptr1 is now invalid, ptr2 owns the resource
std::cout << *ptr2 << std::endl;
return 0;
}
std::shared_ptr
std::shared_ptr is a shared ownership smart pointer that allows multiple shared_ptr objects to share ownership of the same object.
Creating std::shared_ptr
#include <memory>
#include <iostream>
int main() {
// Create a shared_ptr managing an int object
std::shared_ptr<int> ptr(new int(42));
// Access the pointed-to object
std::cout << *ptr << std::endl;
// shared_ptr releases the resource when the reference count reaches zero
return 0;
}
Shared Ownership
Multiple shared_ptr instances can share ownership of the same object.
#include <memory>
#include <iostream>
int main() {
std::shared_ptr<int> ptr1(new int(42));
std::shared_ptr<int> ptr2 = ptr1; // Share ownership
// Both shared_ptr point to the same object
std::cout << *ptr1 << std::endl;
std::cout << *ptr2 << std::endl;
// Resource is released when the last shared_ptr leaves scope
return 0;
}
std::weak_ptr
std::weak_ptr is a weak reference smart pointer that does not increase the reference count and is primarily used to solve circular reference issues.
Creating std::weak_ptr
#include <memory>
#include <iostream>
int main() {
std::shared_ptr<int> ptr(new int(42));
std::weak_ptr<int> weakPtr = ptr; // Create weak_ptr
// Convert to shared_ptr using lock
std::shared_ptr<int> lockedPtr = weakPtr.lock();
if (lockedPtr) {
std::cout << *lockedPtr << std::endl;
} else {
std::cout << "Pointer has expired" << std::endl;
}
return 0;
}
Smart Pointers with Custom Deleters
Custom Deleter
A custom deleter can be provided to smart pointers to perform specific cleanup operations.
#include <memory>
#include <iostream>
struct MyDeleter {
void operator()(int* ptr) const {
std::cout << "Deleting int with value " << *ptr << std::endl;
delete ptr;
}
};
int main() {
std::unique_ptr<int, MyDeleter> ptr(new int(42), MyDeleter());
// Use custom deleter
std::cout << *ptr << std::endl;
return 0;
}
Smart Pointers with Containers
Smart Pointers in Containers
Smart pointers can be used in standard containers.
#include <memory>
#include <vector>
#include <iostream>
int main() {
std::vector<std::shared_ptr<int>> vec;
for (int i = 0; i < 5; ++i) {
vec.push_back(std::make_shared<int>(i));
}
for (auto& ptr : vec) {
std::cout << *ptr << std::endl;
}
return 0;
}
Smart Pointers and RAII
RAII Principle
Smart pointers follow the RAII (Resource Acquisition Is Initialization) principle, acquiring resources during construction and releasing them during destruction.
Using RAII for Resource Management
#include <memory>
#include <iostream>
class Resource {
public:
Resource() { std::cout << "Resource created" << std::endl; }
~Resource() { std::cout << "Resource destroyed" << std::endl; }
};
int main() {
std::unique_ptr<Resource> resource(new Resource());
// Resource is automatically released when leaving scope
return 0;
}
Smart Pointers and Multithreading
Thread Safety
Smart pointers ensure safety in multithreaded environments.
Using std::atomic for Thread Safety
#include <memory>
#include <thread>
#include <iostream>
#include <atomic>
std::atomic<std::shared_ptr<int>> sharedData;
void threadFunction() {
auto data = sharedData.load();
if (data) {
std::cout << "Thread: " << *data << std::endl;
}
}
int main() {
std::shared_ptr<int> data(new int(42));
sharedData.store(data);
std::thread t(threadFunction);
t.join();
return 0;
}
Smart Pointers and Exception Safety
Exception Safety
Smart pointers ensure resource safety even when exceptions occur.
Using Smart Pointers for Exception Safety
#include <memory>
#include <iostream>
class MyClass {
public:
MyClass(int value) {
std::cout << "MyClass constructor called with value " << value << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called" << std::endl;
}
};
int main() {
try {
std::unique_ptr<MyClass> ptr(new MyClass(42));
throw std::runtime_error("Exception occurred");
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
Smart Pointers and Performance
Performance Considerations
While smart pointers provide convenience, they also introduce some performance overhead.
Performance Optimization
In performance-sensitive code, choose the appropriate smart pointer type based on the use case.
#include <memory>
#include <iostream>
int main() {
// Use unique_ptr for better performance
std::unique_ptr<int> ptr(new int(42));
std::cout << *ptr << std::endl;
// Use shared_ptr to share resources
std::shared_ptr<int> ptr1(new int(42));
std::shared_ptr<int> ptr2 = ptr1;
return 0;
}
Smart Pointer Best Practices
Choosing the Right Smart Pointer
Select the appropriate smart pointer type based on specific needs.
Avoiding Circular References
Use std::weak_ptr to resolve circular reference issues.
#include <memory>
#include <iostream>
class A {
public:
std::weak_ptr<B> b;
};
class B {
public:
std::shared_ptr<A> a;
};
int main() {
std::shared_ptr<A> a(new A());
std::shared_ptr<B> b(new B());
a->b = b;
b->a = a;
return 0;
}
Advanced Usage of Smart Pointers
Advanced Usage of Custom Deleters
Complex Deletion Logic
Custom deleters can implement complex cleanup logic, such as closing files or releasing other resources.
Example: Closing a File
#include <memory>
#include <iostream>
#include <fstream>
struct FileDeleter {
void operator()(std::ifstream* file) const {
if (file) {
file->close();
delete file;
}
}
};
int main() {
std::unique_ptr<std::ifstream, FileDeleter> file(
new std::ifstream("example.txt"), FileDeleter());
if (file && file->is_open()) {
std::cout << "File opened successfully" << std::endl;
} else {
std::cout << "Failed to open file" << std::endl;
}
return 0;
}
Using Lambda Expressions
Lambda expressions can simplify custom deleter implementation.
Example: Using Lambda Expression
#include <memory>
#include <iostream>
#include <fstream>
int main() {
std::unique_ptr<std::ifstream> file(
new std::ifstream("example.txt"),
[](std::ifstream* f) {
if (f) {
f->close();
delete f;
}
});
if (file && file->is_open()) {
std::cout << "File opened successfully" << std::endl;
} else {
std::cout << "Failed to open file" << std::endl;
}
return 0;
}
Smart Pointers with STL Containers
Using Smart Pointers in Containers
Using smart pointers in STL containers simplifies resource management.
Example: Using std::vector to Store std::unique_ptr
#include <memory>
#include <vector>
#include <iostream>
int main() {
std::vector<std::unique_ptr<int>> vec;
for (int i = 0; i < 5; ++i) {
vec.push_back(std::make_unique<int>(i));
}
for (const auto& ptr : vec) {
std::cout << *ptr << std::endl;
}
return 0;
}
Using std::shared_ptr in Containers
Using std::shared_ptr in containers allows resource sharing.
Example: Using std::vector to Store std::shared_ptr
#include <memory>
#include <vector>
#include <iostream>
int main() {
std::vector<std::shared_ptr<int>> vec;
for (int i = 0; i < 5; ++i) {
vec.push_back(std::make_shared<int>(i));
}
for (const auto& ptr : vec) {
std::cout << *ptr << std::endl;
}
return 0;
}
Smart Pointers with Inheritance
Smart Pointers in Inheritance Hierarchies
When using smart pointers with inheritance, type safety must be considered.
Example: Smart Pointers in Inheritance
#include <memory>
#include <iostream>
class Base {
public:
virtual void print() const = 0;
};
class Derived : public Base {
public:
void print() const override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
std::shared_ptr<Base> base(new Derived());
base->print();
return 0;
}
Smart Pointers and Type Safety
Type-Safe Smart Pointers
Ensure type safety when using smart pointers.
Example: Type-Safe Smart Pointers
#include <memory>
#include <iostream>
class Base {
public:
virtual void print() const = 0;
};
class Derived : public Base {
public:
void print() const override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
std::shared_ptr<Derived> derived(new Derived());
static_cast<std::shared_ptr<Base>>(derived)->print();
return 0;
}
Smart Pointers and C++20
C++20 introduces new features that further enhance the functionality and usability of smart pointers.
std::launder
std::launder is a utility function introduced in C++20 to bypass certain compiler optimizations and ensure the pointed-to data is valid.
Example: Using std::launder
#include <memory>
#include <iostream>
#include <bit>
class MyClass {
public:
MyClass(int value) : _value(value) {}
int getValue() const { return _value; }
private:
int _value;
};
int main() {
std::unique_ptr<MyClass> ptr(new MyClass(42));
MyClass* rawPtr = std::launder(ptr.get());
std::cout << "Value: " << rawPtr->getValue() << std::endl;
return 0;
}
std::bit_cast
std::bit_cast is a utility function introduced in C++20 for bit-level conversion between different pointer types.
Example: Using std::bit_cast
#include <memory>
#include <iostream>
#include <bit>
class MyClass {
public:
MyClass(int value) : _value(value) {}
int getValue() const { return _value; }
private:
int _value;
};
int main() {
std::unique_ptr<MyClass> ptr(new MyClass(42));
MyClass* rawPtr = std::bit_cast<MyClass*>(ptr.get());
std::cout << "Value: " << rawPtr->getValue() << std::endl;
return 0;
}
std::span
Although std::span is not a smart pointer, combining it with smart pointers improves memory management.
Example: Using std::span with Smart Pointers
#include <memory>
#include <iostream>
#include <span>
class MyClass {
public:
MyClass(int value) : _value(value) {}
int getValue() const { return _value; }
private:
int _value;
};
int main() {
std::unique_ptr<MyClass[]> arr(new MyClass[5]);
for (int i = 0; i < 5; ++i) {
arr[i] = MyClass(i);
}
std::span<MyClass> span(arr.get(), 5);
for (const auto& obj : span) {
std::cout << "Value: " << obj.getValue() << std::endl;
}
return 0;
}
Smart Pointers with Template Metaprogramming
Smart pointers can be combined with template metaprogramming for more flexible resource management.
Example: Using Template Metaprogramming
#include <memory>
#include <iostream>
#include <type_traits>
template<typename T, typename Deleter = std::default_delete<T>>
class CustomUniquePtr {
public:
explicit CustomUniquePtr(T* ptr = nullptr, Deleter del = Deleter()) : _ptr(ptr), _del(del) {}
~CustomUniquePtr() {
_del(_ptr);
}
T* get() const { return _ptr; }
T* release() {
T* temp = _ptr;
_ptr = nullptr;
return temp;
}
CustomUniquePtr& operator=(CustomUniquePtr&& other) noexcept {
_ptr = other._ptr;
_del = other._del;
other._ptr = nullptr;
return *this;
}
private:
T* _ptr;
Deleter _del;
};
int main() {
CustomUniquePtr<int> ptr(new int(42), [](int* p) { delete p; });
std::cout << *ptr.get() << std::endl;
return 0;
}
Smart Pointers with Type Deduction
Smart pointers can leverage C++ type deduction to simplify code.
Example: Using Type Deduction
#include <memory>
#include <iostream>
int main() {
auto ptr = std::make_unique<int>(42);
std::cout << *ptr << std::endl;
auto sharedPtr = std::make_shared<int>(42);
std::cout << *sharedPtr << std::endl;
return 0;
}
Smart Pointers with Memory Pools
Smart pointers can be combined with memory pools to improve allocation efficiency.
Example: Using a Memory Pool
#include <memory>
#include <iostream>
#include <vector>
class MemoryPool {
public:
MemoryPool(size_t size) : _size(size), _freeList(size) {
for (size_t i = 0; i < size; ++i) {
_freeList.push_back(new int(0));
}
}
int* allocate() {
if (_freeList.empty()) {
return new int(0);
}
int* ptr = _freeList.back();
_freeList.pop_back();
return ptr;
}
void deallocate(int* ptr) {
_freeList.push_back(ptr);
}
private:
size_t _size;
std::vector<int*> _freeList;
};
int main() {
MemoryPool pool(10);
auto ptr = std::make_unique<int*>(pool.allocate());
*ptr = 42;
std::cout << *ptr << std::endl;
pool.deallocate(*ptr.release());
return 0;
}
Smart Pointers with Concurrency
Smart pointers can be used with concurrent programming to ensure thread safety.
Example: Using Smart Pointers with Atomic Operations
#include <memory>
#include <thread>
#include <iostream>
#include <atomic>
std::atomic<std::shared_ptr<int>> sharedData;
void threadFunction() {
auto data = sharedData.load();
if (data) {
std::cout << "Thread: " << *data << std::endl;
}
}
int main() {
std::shared_ptr<int> data(new int(42));
sharedData.store(data);
std::thread t(threadFunction);
t.join();
return 0;
}
Smart Pointers and Exception Safety
Smart pointers ensure resource safety even when exceptions occur.
Example: Exception-Safe Smart Pointers
#include <memory>
#include <iostream>
#include <stdexcept>
class MyClass {
public:
MyClass(int value) {
std::cout << "MyClass constructor called with value " << value << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called" << std::endl;
}
};
int main() {
try {
std::unique_ptr<MyClass> ptr(new MyClass(42));
throw std::runtime_error("Exception occurred");
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
Smart Pointers with Design Patterns
Smart pointers can be applied in various design patterns, such as the factory pattern, singleton pattern, etc.
Example: Factory Pattern with Smart Pointers
#include <memory>
#include <iostream>
class Base {
public:
virtual void print() const = 0;
};
class Derived : public Base {
public:
void print() const override {
std::cout << "Derived class" << std::endl;
}
};
class Factory {
public:
static std::unique_ptr<Base> createBase() {
return std::make_unique<Derived>();
}
};
int main() {
auto base = Factory::createBase();
base->print();
return 0;
}
Smart Pointers and Performance Optimization
While smart pointers provide convenience, they introduce some performance overhead. Reasonable design and usage can reduce performance loss.
Example: Performance Optimization
#include <memory>
#include <iostream>
int main() {
// Use unique_ptr for better performance
std::unique_ptr<int> uniquePtr(new int(42));
std::cout << *uniquePtr << std::endl;
// Use shared_ptr to share resources
std::shared_ptr<int> sharedPtr(new int(42));
std::shared_ptr<int> sharedPtr2 = sharedPtr;
return 0;
}
Smart Pointers and Memory Leak Detection
Memory Leak Detection Tools
Smart pointers help reduce the risk of memory leaks, but tools are sometimes needed to ensure no leaks exist.
Example: Using Valgrind for Memory Leak Detection
Assume a simple C++ program with a potential memory leak:
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called" << std::endl;
}
};
int main() {
MyClass* ptr = new MyClass();
// Forgot to delete the pointer
std::cout << "End of main" << std::endl;
return 0;
}
Using Valgrind to Detect Memory Leaks:
valgrind --leak-check=full ./your_program
Valgrind output may look like:
==1234== HEAP SUMMARY:
==1234== in use at exit: 8 bytes in 1 blocks
==1234== total heap usage: 1 allocs, 0 frees, 8 bytes allocated
==1234==
==1234== 8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1234== at 0x4C30A9F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1234== by 0x108A4E: MyClass::MyClass() (MyClass.cpp:4)
==1234== by 0x108C1B: main (main.cpp:11)
==1234==
==1234== LEAK SUMMARY:
==1234== definitely lost: 8 bytes in 1 blocks
==1234== indirectly lost: 0 bytes in 0 blocks
==1234== possibly lost: 0 bytes in 0 blocks
==1234== still reachable: 0 bytes in 0 blocks
==1234== suppressed: 0 bytes in 0 blocks
The output shows a definite memory leak.
Using Smart Pointers to Avoid Memory Leaks
Modify the previous program to use std::unique_ptr:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called" << std::endl;
}
};
int main() {
std::unique_ptr<MyClass> ptr(new MyClass());
std::cout << "End of main" << std::endl;
return 0;
}
Run Valgrind again:
valgrind --leak-check=full ./your_program
Valgrind output shows no memory leaks:
==1234== HEAP SUMMARY:
==1234== in use at exit: 0 bytes in 0 blocks
==1234== total heap usage: 1 allocs, 1 frees, 8 bytes allocated
==1234==
==1234== All heap blocks were freed -- no leaks are possible
==1234==
==1234== For counts of detected and suppressed errors, rerun with: -v
==1234== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)



