Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about an example from rule 9-3-1
#5
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:

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>
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 3 Guest(s)