Use of new
or make_unique
instead of more
efficient make_shared
Using new
or make_unique
to initialize or
reset shared_ptr
results in additional memory allocation
Since R2021a
Description
This defect occurs when you use:
new
ormake_unique
to initialize ashared_ptr
instance. For example:std::shared_ptr<T> p1(new T()); std::shared_ptr<T> p2(make_unique<T>());
new
to reset ashared_ptr
instance. For example:std::shared_ptr<T> p1; //... p1.reset(new T);
You use shared_ptr
instances when you want multiple smart
pointers to own and manage the same object. The instances also share a control block that
holds a count of the number of instances that own the managed object.
Polyspace® does not flag the use of new
to initialize a
shared_ptr
instance in private or protected constructors. For example, no
defect is raised on the use of new
in this code
snippet:
class PrivateCTor { public: static std::shared_ptr<PrivateCTor> makeOne() { return std::shared_ptr<PrivateCTor>(new PrivateCTor); } private: PrivateCTor(); };
Risk
When you use new
or make_unique
to initialize a
shared_ptr
instance, an additional allocation operation creates storage
for the control block. The address of the additional allocation might be in a different
memory page or outside the data-cache compared to the address of the managed object.
Fix
Use std::make_shared
to initialize a shared_ptr
instance. The function performs a single allocation operation with enough memory to store
the managed object and the control block.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language: C++ |
Default: Off |
Command-Line Syntax:
MISSING_MAKE_SHARED |
Impact: Low |
Version History
Introduced in R2021a
See Also
Find defects
(-checkers)
| AUTOSAR C++14 Rule
A20-8-6
| AUTOSAR C++14 Rule
A18-5-2
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)