new or make_unique instead of more
efficient make_sharedUsing new or make_unique to initialize or
reset shared_ptr results in additional memory allocation
This defect occurs when you use:
new or make_unique to initialize a
shared_ptr instance. For
example:
std::shared_ptr<T> p1(new T()); std::shared_ptr<T> p2(make_unique<T>());
new to reset a shared_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();
};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.
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.
| Group: Performance |
| Language: C++ |
| Default: Off |
Command-Line Syntax:
MISSING_MAKE_SHARED |
| Impact: Low |