07-04-2017, 09:11 AM
As soon as you store a reference, it becomes class data.
I slightly reworked the example, to make it even more obvious what evil code you could write, if this was not treated a violation of 9-3-1:
I slightly reworked the example, to make it even more obvious what evil code you could write, if this was not treated a violation of 9-3-1:
Code:
#include
namespace nMISRA
{
class C {
public:
C ( int32_t &b_ ) : b( b_ ) { }
int32_t *getB () const
{
return &b; // Non-compliant
}
int32_t getState(void) const{return b;}
private:
int32_t &b;
};
void foo(const C& rhs, int32_t s)
{
*rhs.getB() = 1;// !!!wow, a const ref and a const member change the state of the object without even knowing the variable defined in main!!!
}
}
int32_t main(void)
{
int32_t ret = 0;
int32_t state = 0;
nMISRA::C c(state);
nMISRA::foo(c, 1);
if (c.getState() != 0)
ret = -1;// error
return ret;
}
<t></t>