c++constexprmember-functions

For a member function, are constexpr, const reference return type, and const qualification mutually independent?


Using

g++ -std=gnu++17 -Werror -Wall -Wextra

the following code compiles without warning:

struct Mutable {
  int x;
};

class State {
public:
  constexpr const Mutable &Immutable() const {
    return mutable_;
  }

private:
  Mutable mutable_;
} state_instance;

From what I've read, every const in that signature means something different:

Are there any redundancies?

This is not the same question as e.g.

which do not describe the constness of returned references.


Solution

  • Each of these is completely independent of each other.

    A function which can produce a constant expression may modify any of its parameters (including the implicit this). Just because the result of the expression can be determined at compile-time does not mean nothing was changed when computing that result. And return values which are constant expressions can in fact be modified during constant evaluation, depending on what you're doing with them.

    There is no inherent connection between any function parameters (including the implicit this) and a function's return value. As such, whether you can modify a returned reference is independent of whether a function will modify a parameter (again, including the implicit this).