This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 16.5.1 - The logical AND and logical OR operators shall not be overloaded
Category: Required
Analysis: Decidable,Single Translation Unit
Rationale
Logical AND and logical OR operators are transformed into function calls. Whilst the overloaded operators obey the rules for syntax and evaluation
order defined within the C++ Standard, both operands will always be evaluated. As it may be unclear if a particular use of a logical operator results
in a call to an overloaded operator, a developer may incorrectly believe that short-circuit evaluation will occur.
Note: the order of evaluation of the operands was unspecified when using overload operators in versions of C++ prior to C++17.
Example
In the following example, instantiation of the template function f with AutomatedCar results in the built-in
operator&& being used, with AutomatedCar::increaseSpeed only being called if AutomatedCar::isOvertaking
returns true.
If f is instantiated with Car, the overload of operator&& is used. As this does not have
short-circuit behaviour, Car::increaseSpeed is always called, irrespective of the value returned by Car::isOvertaking.
class FuzzyBool {};
class Car
{
public:
FuzzyBool isOvertaking();
bool increaseSpeed();
};
class AutomatedCar
{
public:
bool isOvertaking();
bool increaseSpeed();
};
bool operator&&( FuzzyBool fb, bool b ); // Non-compliant
template< class Vehicle >
void f( Vehicle & v )
{
if ( v.isOvertaking() && v.increaseSpeed() )
{
}
}
Copyright The MISRA Consortium Limited © 2023