Insufficient pointer usage
Modern C++ provides smart pointers such as std::unique_ptr
and std::shared_ptr
to manage dynamic memory more safely and efficiently. It’s generally better to use std::unique_ptr
instead of raw pointers for exclusive ownership. When multiple actors need to share ownership of a resource, std::shared_ptr
can be used. However, there are common issues related to the misuse of std::shared_ptr
.
Building std::shared_ptr
Using the constructor of std::shared_ptr
to create an object leads to separate allocations for the control block and the managed object:
std::shared_ptr<int> create() { std::shared_ptr<int> ptr(new int(42)); return ptr; }
A better approach is to use std::make_shared
, which combines the allocations into a single memory block, improving performance and cache locality:
std::shared_ptr<int> create() { return std::make_shared<int>(42);...