Main Content

AUTOSAR C++14 Rule A13-1-3

User defined literals operators shall only perform conversion of passed parameters

Since R2021a

Description

Rule Definition

User defined literals operators shall only perform conversion of passed parameters.

Rationale

User-defined literal operators are expected to simply convert their parameters to the operator return type. If your operators perform operations other than this conversion, reviewers or other developers who use the operator might find this behavior unexpected.

For instance, the operator _km is expected to convert a long long int parameter to the type Distance:

Distance operator"" _km(long long int param) {
  ...
}
Any other operation performed by this operator might be unexpected.

Polyspace Implementation

The checker flags user-defined literal operators that have one of these issues:

  • The operator has a return type void. Such an operator cannot return the converted parameter.

  • The operator does not even use its parameter, let alone convert its parameter to the operator return type.

  • The operator performs an operation that has or might have side-effects. Such an operator defies the expectation that a user-defined literal operator only converts its parameter. For instance, the operator might update a global or static variable (definite side-effect) or call another function (possible side-effect). In the latter case, look into the callee function body to make sure it does not have side effects.

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>

struct Distance {
   unsigned long long int distparam;
   constexpr explicit Distance(unsigned long long int v) : distparam(v) {}
};

constexpr Distance operator"" _m(unsigned long long int distparam) //Compliant
{
   return Distance(distparam); 
}

static void updateNumberOfConversions() {
   static std::int32_t numberOfConversions = 0;
   numberOfConversions++;
}

constexpr Distance operator"" _km(unsigned long long int distparam) //Noncompliant
{
   updateNumberOfConversions();
   return Distance(distparam); 
}

In this example, the operator _m simply converts its parameter to the return type Distance and does not violate the rule. The operator _km, in addition to converting its parameter, also calls the function updateNumberOfConversions, which modifies a static variable. Therefore, the operator _km has additional side effects and violates the rule.

Check Information

Group: Overloading
Category: Required, Automated

Version History

Introduced in R2021a