Main Content

MISRA C++:2023 Rule 16.5.2

The address-of operator shall not be overloaded

Since R2024b

Description

Rule Definition

The address-of operator shall not be overloaded.

Rationale

Overloading the address-of (the unary &) operator in a class can lead to undefined behavior if you use C++ version C++11 or older. Overloading the unary & operator is unspecified behavior if you use C++ version C++14 or newer. The undefined or unspecified behavior occurs if both of these conditions are true:

  • You take the address of an incomplete type.

  • The type contains an overloaded unary & operator.

Overloading the & operator makes the code harder to understand because *&a might not evaluate to a.

Polyspace Implementation

Polyspace® reports a violation if you overload the unary & 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 example, the address-of operator is overloaded in the class myclass. In the source file file1.cpp, because myclass.h is not included, myclass becomes an incomplete type. Taking address of the myclass object a by using the built-in unary & operator then becomes an undefined or unspecified behavior depending on your version of C++. Polyspace reports a violation on the overloading of the unary & operator. To avoid unexpected errors, do not overload the unary & operator.

//myclass.h
class myclass{
public:
myclass * operator&();  //Noncompliant
};
//file1.cpp
class myclass; //Incomplete type

void foo(myclass& a){
&a; // undefined or unspecified behavior;
}
//file2.cpp
#include"myclass.h"
void foo2(myclass& a){
&a; //Uses user-defined operator &
}
 

Check Information

Group: Overloading
Category: Required

Version History

Introduced in R2024b