This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 16.5.2
Category: Required
Analysis Type: Decidable,Single Translation Unit
Rationale
Taking the address of an object of incomplete type where the complete type contains a user-declared operator&
results in
undefined behaviour (until C++11) or unspecified behaviour (since C++11).
Overloading the &
operator can make code harder to understand as *&a
may not give the same result as
a
.
Note: std::addressof
will always return the address of an object without there being a risk of undefined or
unspecified behaviour.
Example
// A.h
class A
{
public:
A * operator&(); // Non-compliant
};
// f1.cc
class A;
void f1( A & a )
{
&a; // Undefined or unspecified behaviour
}
// f2.cc
#include "A.h"
void f2( A & a )
{
&a; // Uses user-defined operator&
}
Copyright The MISRA Consortium Limited © 2023