Main Content

MISRA C++:2023 Rule 8.3.2

The built-in unary + operator should not be used

Since R2024b

Description

Rule Definition

The built-in unary + operator should not be used.

Rationale

When you use the operator+ with only one operator:

  • If the operand is a built-in integral type, the unary + operator triggers an integral promotion.

  • If the operand is a function name or lambda, the unary + operator converts the operator into a function pointer.

When these behavior are required, use an explicit cast instead of the unary + operator. Use of an explicit cast makes the code easier to read and communicates the desired code behavior clearly. Using the unary + operator can hide potential issues such as missing operands of the binary + operator or mistakenly using =+ instead of +=. These issues can be difficult to diagnose because the code compiles but shows unexpected behavior.

Polyspace Implementation

The rule checker reports violations on uses of the built-in operator+ with one parameter but does not flag uses of any user-defined operator+.

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

In this code, when the built-in unary + operator is used, it is not clear if the + operator is intentionally used or if an operand is missing.

class Foo {
public:
	Foo(int i): data(i) {}
	Foo operator+() const {
		return Foo(data);
	}
private:
	int data;
};

void myFunc(unsigned char inString) {
	auto obj = +inString;              // Noncompliant

	obj =+ 1;                   // Noncompliant 

	Foo myClass(42);
	Foo myClass2 = +myClass;            // Compliant - user defined operator

	auto myLambda = +[]() {};       // Noncompliant
}
It is possible that the unary + operator is used intentionally. It is also possible that the + operator is missing an operand, perhaps by mistake. Such usages are confusing. Because this code compiles, it is difficult to debug potential issues such as missing operands of the binary + operator or mistaken use of =+ instead of +=.

Check Information

Group: Expressions
Category: Advisory

Version History

Introduced in R2024b