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. 1
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_ptrobject usingstd::make_uniqueorstd::shared_ptrobject usingstd::make_sharedis exception-safe and improves run-time performance. For instance, if dynamic memory allocation with thenewoperator 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_ptrobject (orboost::unique_ptrobject) from the raw pointer returned by thenewoperator.The creation of an
std::shared_ptrobject (orboost::shared_ptrobject) from the raw pointer returned by thenewoperator.
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
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.