AutosarC++17_10-A18.1.5ΒΆ

The std::unique_ptr shall not be passed to a function by const reference

Required inputs: IR

Rationale

A parameter of type const std::unique_ptr& provides constness benefits for std::unique_ptr only, not for an object it is pointing to. This may lead to confusion whether a function is allowed to modify the underlying pointer or not.

Instead, const pointer or const reference to the underlying object should be passed.

Example
// $Id: A18-1-5.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
#include <memory>

void Fn1(std::unique_ptr<std::int32_t> ptr) // Compliant
{
  // fn1() now owns ptr
}

void Fn2(std::unique_ptr<std::int32_t> &ptr) // Compliant
{
  // fn2() is explicitly allowed to make a ptr to refer to a different object
}

void Fn3(const std::unique_ptr<std::int32_t> &ptr) // Non-compliant
{
  // fn3 takes ptr by const reference but still it is able to make a ptr to
  // refer to a different object

  *ptr = 10; // No compilation error
}

void Fn4(const std::int32_t *ptr) // Compliant
{
  // fn4 takes a const raw pointer

  //*ptr = 10;     // Compilation error
}

void Fn5() {
  Fn1(std::make_unique<std::int32_t>(0));

  std::unique_ptr<std::int32_t> ptr = std::make_unique<std::int32_t>(0);
  Fn2(ptr);
  Fn3(ptr);
  Fn4(ptr.get());
}
See Also
  • HIC++ v4.0 [8]: 8.2.4 Do not pass std::unique_ptr by const reference.
  • C++ Core Guidelines [10]: R.33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget.

Possible Messages

Key

Text

Severity

Disabled

const_ref_unique_ptr

const std::unique_ptr& as parameter.

None

False

Options