Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A7-1-2: Is it really intented to mark also functions as constexpr?

A7-1-2 says:
The constexpr specifier shall be used for values that can be determined at compile time.

So it only talks about "values", not "functions". However, in the example, it says the following code is not compliant, because the function Pow1 "can be" constexpr but is not marked as such:

std::int32_t Pow1(std::int32_t number)
    return (number * number);
void Fn()
    const std::int32_t threeSquare = Pow1(3); // Non-compliant, possible run-time evaluation

On the other hand, examples are not normative - the title of the rule is.

Therefore I ask: is rule A7-1-2 intended to mark every single function as constexpr if it _can_ be constexpr?

In my opinion, this has negative consequences. Constexpr-ness of a function should be a careful design decision, not something added blindly to comply with a static analysis tool. It limits the way an author can choose to implement a given function. Maybe today the function _can_ be constexpr, but tomorrow as an author I want to refactor the implementation to e.g. use more modern libraries from STL, which don't have constexpr support in C++14 (for example, a silly std::array::operator[] is not supported in constexpr functions). Changing the implementation would require removing constexpr and updating also all the clients (which could dramatically cascade into second-order functions and so on). Or the alternative would be to be locked into constexpr and have to resort to older-style code to implement it (e.g. use a C array instead of std::array), making the function ultimately less safe and violating other Autosar rules.

It’s not the intention of this rule to force constexpr to be added to all functions who’s return value can be evaluated at compile time.

The example  const std::int32_t threeSquare = Pow1(3);  should be shown as compliant, because Pow1 has to be evaluated at run-time as its not constexpr.

However,  const std::int32_t  fourSquare = Pow2(4);    would be non-compliant, as Pow2 is declared constexpr, and Pow2(4) can be evaluated at compile-time, so foursquare can be declared constexpr.
Posted by and on behalf of
the MISRA C++ Working Group
Thank you for the clarification!
Thread closed
Posted by and on behalf of
the MISRA C++ Working Group

Forum Jump:

Users browsing this thread: 1 Guest(s)