14-04-2022, 01:32 PM
(This post was last modified: 20-04-2022, 07:57 AM by kth.
Edit Reason: typo
)
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
The rationale of Con.2 explicitly uses "observable state":
Motivation of this post is that our static analysis tool currently reports a M9-3-3 finding for this code:
A similar example with shared_ptr:
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?
- 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?