std::make_unique shall be used to construct objects owned by std::unique_ptr
std::make_unique shall be used to construct objects owned by std::unique_ptr.
Instead of allocating memory by using the new operator and converting
the resulting raw pointer to an std::unique_ptr object, for
instance:
class numberClass {
public:
numberClass(int n): number(n){}
private:
int number;
}
int aNumber=1;
std::unique_ptr<numberClass> numberPtr (new numberClass(aNumber)); std::unique_ptr object directly using the
std::make_unique function. For
instance:auto numberPtr = std::make_unique<numberClass>(aNumber);
Using std::make_unique is preferred because:
The creation of the std::unique_ptr object using
std::make_unique is exception-safe. Otherwise, an exception can
occur between the dynamic memory allocation with the new operator
and the subsequent conversion, leading to a memory leak. An exception causes a memory
leak only in certain contexts, for instance, when the
std::unique_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.
The checker flags the creation of an std::unique_ptr object (or
boost::unique_ptr object) from the raw pointer returned by the
new operator.
If you expect a rule violation but do not see it, refer to the documentation for Polyspace® Bug Finder™ or Polyspace Bug Finder Server™.
| Group: General utilities library |
| Category: Required, Automated |