This document demonstrates best practices and common patterns for using std::unique_ptr, std::shared_ptr, and std::weak_ptr in modern C++.
Note:
Nomain()function is provided. These examples are intended for inclusion in other code or for use in unit tests or documentation snippets.
-
Creating Circular References with
shared_ptr- If two objects own each other via
shared_ptr, they will never be destroyed (memory leak). - Solution: Use
std::weak_ptrfor back-references or observer relationships.
- If two objects own each other via
-
Unnecessary Use of
shared_ptr- Overusing
shared_ptradds overhead and can make ownership unclear. - Solution: Prefer
std::unique_ptrfor exclusive ownership. Useshared_ptronly when shared ownership is truly needed.
- Overusing
-
Mixing Raw Pointers and Smart Pointers
- Don’t create multiple smart pointers from the same raw pointer. This can cause double deletion.
- Solution: Always transfer ownership to a smart pointer immediately after allocation.
-
Dangling
weak_ptr- Accessing a
weak_ptrwithout checking if it’s expired can lead to undefined behavior. - Solution: Always use
lock()and check the result before using the object.
- Accessing a
-
Storing Smart Pointers for Non-Owning Access
- Don’t use smart pointers just to access an object you don’t own.
- Solution: Use raw pointers or references for non-owning access.
-
Forgetting to Use
std::make_unique/std::make_shared- Using
newdirectly with smart pointers is error-prone and less efficient. - Solution: Use
std::make_uniqueandstd::make_sharedfor allocation.
- Using
-
Not Understanding Ownership Semantics
- Passing smart pointers by value can transfer or share ownership unexpectedly.
- Solution: Pass by reference or const reference when you don’t want to transfer/share ownership.
-
Custom Deleters
- If you use a custom deleter, make sure it matches the allocation method.
- Solution: Only use custom deleters when necessary and ensure correctness.
Avoiding these pitfalls will help you write safer and more maintainable C++ code with smart pointers.