Main Content

AUTOSAR C++14 Rule A13-2-2

A binary arithmetic operator and a bitwise operator shall return a "prvalue"

Since R2021a

Description

Rule Definition

A binary arithmetic operator and a bitwise operator shall return a "prvalue".

Rationale

Binary arithmetic operators such as operator+() and bitwise operators such as operator|() must return an object of type T by value without qualifiers (and not references, T&, or pointers ,T*). This requirement makes the return types consistent with the implementation of the same operators in the C++ Standard Library. A developer familiar with the standard operators can easily work with the overloaded forms of the operators.

A prvalue or pure rvalue is an object that does not have a name, cannot be pointed to or referenced, but can still be moved from. For instance, the result of a call to a function that returns by value is a prvalue.

Polyspace Implementation

The checker flags implementations of binary and bitwise operators that return:

  • A type with a qualifier such as const or volatile.

  • A pointer or reference to another type.

Operators flagged by the checker include:

  • Binary operators such as operator+(), operator*(), operator/(), and so on.

  • Bitwise operators such as operator&(), operator|(), operator<<(), and so on.

    Note that the checker does not show violations on operator<<() and operator>>() that return std::basic_istream, std::basic_ostream, or std::basic_iostream types.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>

class A
{
};
class B
{
};

A* operator+(A const&, A const&) noexcept //Noncompliant
{
  return new A{};
}
B operator+(B const&, B const&) noexcept //Compliant
{
  return B{};
}

const A operator*(A const&, A const&) noexcept //Noncompliant
{
  return A{};
}
B operator*(B const&, B const&) noexcept //Compliant
{
  return B{};
}

std::int32_t* operator/(A const&, A const&) noexcept //Noncompliant
{
  return 0;
}
std::int32_t operator/(B const&, B const&) noexcept //Compliant
{
  return 0;
}

In this example, the operator overloads that take operands of type A return objects that are not prvalues. Hence, these operators violate the rule. For instance:

  • operator+ and operator/ return pointers to objects.

  • operator* returns a const-qualified object.

The equivalent operator overloads for type B return objects by value without qualifiers and comply with the rule.

Check Information

Group: Overloading
Category: Required, Automated

Version History

Introduced in R2021a