AutosarC++17_10-M9.3.1

const member functions shall not return non-const pointers or references to class-data

Required inputs: IR

Rationale

When an object is declared with const class type, only const member functions can be invoked on that object. The common expectation of const member functions is that the state of the object may not be modified when invoking the functions. However, returning a non-const pointer or reference to class-data from a const function allows a modification to the conceptual state of an object.

Example
class C 
{
public:
C ( int32_t & b_ ) : a ( new int32_t [ 10 ] ), b ( b_ )
{
}
int32_t * getA () const // Non-compliant
// Returns non const pointer to data
{
return a;
}
int32_t * getB () const // Non-compliant
// Returns non const pointer to data
{
return &b;
} const int32_t * getC () const // Compliant
// Returns const pointer to data
{
return &b;
}
private:
int32_t * a;
int32_t & b;
};
void fn ( C const & c )
{
c.getA()[ 0 ] = 0; // Modification to conceptual state of C
*c.getB() = 0; // Modification to conceptual state of C
fn2 ( c.getC() ); // Value can be used,
*c.getC() = 0; // but compiler will report an error here
}

Note

For legal reasons, this rule’s description is not part of the public documentation.