AutosarC++17_03-A12.8.7ΒΆ

Assignment operators should be declared with the ref-qualifier &

Required inputs: IR

Rationale

User declared assignment operators differ from built-in operators in a way that they accept rvalues as parameters, which is confusing. Adding & to the function declaration prohibits rvalue parameters and ensures that all of the calls can only be made on lvalue objects, which results with the same behavior as for built-in types.

Note that this rule applies to all assignment operators, e.g. operator=(), operator*=(), operator+=.

Example
// $Id: A12-8-7.cpp 271687 2017-03-23 08:57:35Z piotr.tanski $
#include <cstdint>
class A {
public:
A() = default;
A &operator*=(std::int32_t i) // Non-compliant
{
// ...
return *this;
}
};
A f1() noexcept { return A{}; }
class B {
public:
B() = default;
B &operator*=(std::int32_t) & // Compliant
{
// ...
return *this;
}
};
B f2() noexcept { return B{}; }
std::int32_t f3() noexcept { return 1; }
int main(int, char **) {
f1() *= 10; // Temporary result of f1() multiplied by 10. No compile-time
      // error.
;
// f2() *= 10; // Compile-time error due to ref-qualifier
;
// f3() *= 10;    // Compile-time error on built-in type
}
See Also
  • HIC++ v4.0 [8]: 12.5.7 Declare assignment operators with the ref-qualifier &.
  • cppreference.com [15]: Assignment operators.

Possible Messages

Key

Text

Severity

Disabled

asgn_missing

Assignment operators should be declared with the ref-qualifier &.

None

False

Options