AUTOSAR C++14 Rule A20-8-6
std::make_shared shall be used to construct objects owned by std::shared_ptr
Since R2020b
Description
Rule Definition
std::make_shared shall be used to construct objects owned by std::shared_ptr.
Rationale
Create a std::shared_ptr
object directly by using the
std::make_shared
function:
auto numberPtr = std::make_shared<numberClass>(aNumber);
std::shared_ptr
objects by converting raw pointers to dynamic
memory:class numberClass { public: numberClass(int n): number(n){} private: int number; } int aNumber=1; std::shared_ptr<numberClass> numberPtr (new numberClass(aNumber));
Using std::make_shared
is preferred because:
The creation of the
std::shared_ptr
object is performed in a single dynamic memory allocation and improves run-time performance. Otherwise, creating a raw pointer by using thenew
operator requires one dynamic memory allocation and converting the raw pointer to anstd::shared_ptr
object requires a second allocation. The second allocation creates a control block that keeps track of the reference count of the shared resource and makes thestd::shared_ptr
object aware of all pointers to the shared resource.The creation of the
std::shared_ptr
object usingstd::make_shared
is exception-safe. Otherwise, an exception can occur between the dynamic memory allocation with thenew
operator and the subsequent conversion, leading to a memory leak. An exception causes a memory leak only in certain contexts, for instance, when thestd::shared_ptr
object is created in an argument of a multi-parameter function and another function argument evaluation throws an exception.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::shared_ptr
object (or
boost::shared_ptr
object) from the raw pointer returned by the
new
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: Required, Automated |