Rule Definition
By implementing class interfaces with member functions the implementation retains more control over how the object state can be modified and helps to allow a class to be maintained without affecting clients. Returning a handle to class-data allows for clients to modify the state of the object without using any interfaces.
Remediation
A resource can be used by the class but is not class-data, non-const handles to this data may be returned.
Violation Code Sample
class C
{
public:
int32_t & getA () // Non-compliant
{
return a;
}
private:
int32_t a;
};
void b ( C & c )
{
int32_t & a_ref = c.getA ();
a_ref = 10; // External modification of private C::a
}
c.getA() returns a reference to the member, which is then stored and modified by a_ref. The
class, therefore, has no control over changes to its state.
Fixed Code Sample
class C
{
public:
C ( int32_t * shared ) : m_shared ( shared )
{
}
int32_t * getA ()
{
return m_shared; // Compliant - m_shared is not class-data
}
private:
int32_t * m_shared;
};
Reference
MISRA C++ 2008, 9-3-2: Member functions shall not return non-const handles to class-data.
AUTOSAR C++ 2014, A9-3-1: Member functions shall not return non-const “raw” pointers or references to private or protected data owned by the class.
Related Technologies
Technical Criterion
Programming Practices - Modularity and OO Encapsulation Conformity
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.