Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
M9-3-3 and observable state
#1
The AUTOSAR Guidelines for the use of the C++14 language in critical and safety-related systems (Release 19-03/latest) basically reuse MISRA C++ Rule 9-3-3 as M9-3-3 but add two clarification notes and a reference to C++ Core Guidelines 
  • Con.2: By default, make member functions const.

The rationale of Con.2 explicitly uses "observable state": 

Quote:Reason A member function should be marked const unless it changes the object’s observable state. This gives a more precise statement of design intent, better readability, more errors caught by the compiler, and sometimes more optimization opportunities.

Motivation of this post is that our static analysis tool currently reports a M9-3-3 finding for this code:
Code:
class B final {
public:
  B(int* dest) : p_{dest} {}
 
  int& Get() { return *p_; }  // M9-3-3 reported
 
  // Here adding const to Get() does not lead to a compiler error, due to the indirection that is introduced with
  // the pointer 'p_'. However, adding const without changing the return type to 'const int&' is missleading.
private:
  int val_{0};
  int* p_{&val_};
};



A similar example with shared_ptr:
Code:
class Data
{
  public:
    // changes the observable state
    void Set(int val) noexcept
    {
      val_ = val;
    }

    int Get() const noexcept
    {
      return val_;
    }

  private:
    int val_;
};

class WithSharedPtr {
  public:

    void SetValue() {  //< M9-3-3 Method can be declared const reported here
      sptr->Set(3);
    }

    void ChangePtr() {
      sptr = std::make_shared<Data>();
    }

    int GetValue() const {
      return sptr->Get();
    }

  private:
    std::shared_ptr<Data> sptr = std::make_shared<Data>();
};

For both findings adding const is technically possible, but the observable state is changed.

My question: what is the correct interpretation of MISRA C++ 9-3-3 and AUTOSAR M9-3-3?
Reply


Messages In This Thread
M9-3-3 and observable state - by kth - 14-04-2022, 01:32 PM
RE: M9-3-3 and observable state - by cgpzs - 20-04-2022, 07:50 AM
RE: M9-3-3 and observable state - by kth - 20-04-2022, 08:22 AM
RE: M9-3-3 and observable state - by misra cpp - 29-04-2022, 12:20 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)