MISRA C++:2023 Rule 23.11.1
The raw pointer constructors of std::shared_ptr
and
std::unique_ptr
should not be used
Since R2024b
Description
Rule Definition
The raw pointer constructors of std::shared_ptr
and
std::unique_ptr
should not be used.
Rationale
Instead of allocating memory by using the new
operator and converting the resulting raw pointer to an std::unique_ptr
or std::shared_ptr
object, for instance:
class numberClass { public: numberClass(int n): number(n){} private: int number; } int aNumber=1; std::unique_ptr<numberClass> numberUniquePtr (new numberClass(aNumber)); std::shared_ptr<numberClass> numberSharedPtr (new numberClass(aNumber));
std::unique_ptr
or std::shared_ptr
object directly using the std::make_unique
or std::make_shared
function. For instance:auto numberUniquePtr = std::make_unique<numberClass>(aNumber); auto numberSharedPtr = std::make_shared<numberClass>(aNumber);
Using std::make_unique
or std::make_shared
is preferred because:
The creation of the
std::unique_ptr
object usingstd::make_unique
orstd::shared_ptr
object usingstd::make_shared
is exception-safe and improves run-time performance. For instance, if dynamic memory allocation with thenew
operator and the subsequent conversion happened in separate steps, an exception can occur between the steps, leading to a memory leak.You can use a more concise syntax. You do not have to repeat the data type of the object that is dynamically allocated.
Polyspace Implementation
The checker flags:
The creation of an
std::unique_ptr
object (orboost::unique_ptr
object) from the raw pointer returned by thenew
operator.The creation of an
std::shared_ptr
object (orboost::shared_ptr
object) from the raw pointer returned by thenew
operator.
Troubleshooting
If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: General utilities library |
Category: Advisory |
Version History
Introduced in R2024b