AutosarC++17_03-A18.1.5ΒΆ
The std::unique_ptr shall not be passed to a function by const reference
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
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 271687 2017-03-23 08:57:35Z piotr.tanski $
#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
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.