AutosarC++18_03-A20.8.5

std::make_unique shall be used to construct objects owned by std::unique_ptr

Required inputs: IR

Rationale

Using std::make_unique to create instances of std::unique_ptr<T> provides object allocation without explicit call of new function, see A18-5-2. It also ensures exception safety in complex expressions and prevents from memory leaks caused by unspecified- evaluation order-expressions.

Exceptions

It is allowed to use explicit new function call to create an instance of std::unique_ptr<T>, if it requires a custom deleter.

Example
// $Id: A20-8-5.cpp 308507 2018-02-21 13:23:57Z michal.szczepankiewicz $
#include <cstdint>
#include <functional>
#include <memory>

struct A {
  A() { throw std::runtime_error("example"); }
  A(std::uint8_t xx, std::uint8_t yy) : x(xx), y(yy) {}
  std::uint8_t x;
  std::uint8_t y;
};

void Foo(std::unique_ptr<A> a, std::unique_ptr<A> b) {}

int main(void) {
  // compliant
  std::unique_ptr<A> upA = std::make_unique<A>(4, 6);
  // non-compliant
  std::unique_ptr<A> upA2 = std::unique_ptr<A>(new A(5, 7));

  // non-compliant, potential memory leak, as A class constructor throws
  Foo(std::unique_ptr<A>(new A()), std::unique_ptr<A>(new A()));
  // non-compliant, potential memory leak, as A class constructor throws
  Foo(std::make_unique<A>(4, 6), std::unique_ptr<A>(new A()));
  // compliant, no memory leaks
  Foo(std::make_unique<A>(4, 6), std::make_unique<A>(4, 6));

  // compliant by exception
  std::unique_ptr<A, std::function<void(A *)>> ptr(new A(4, 5),
                                                   [](A *b) { deleteb; });

  return 0;
}
See Also
  • C++ Core Guidelines [10]: R.23: Use make_unique() to make unique_ptrs
  • C++ Core Guidelines [10]: C.150: Use make_unique() to construct objects owned by unique_ptrs

Possible Messages

Key

Text

Severity

Disabled

shared_ctor_used

Call to constructor of std::shared_ptr rather than using std::make_shared.

None

False

unique_ctor_used

Call to constructor of std::unique_ptr rather than using std::make_unique.

None

False

Options

consider_std_shared

consider_std_shared : bool = False

Whether calls to the constructor of std::shared_ptr should be reported.
 

consider_std_unique

consider_std_unique : bool = True

Whether calls to the constructor of std::unique_ptr should be reported.
 

only_suggest_semantically_identical_replacements

only_suggest_semantically_identical_replacements : bool = True

Only suggest replacing constructor calls by make_shared or make_unique if the replacement would be semantically equivalent. For instance, std::shared_ptr{new B} is equivalent to std::make_shared(), but std::shared_ptr{b} is not equivalent to either std::make_shared() or std::make_shared(b).