What is the purpose of marking the set function (setter) as constexpr?

The need arise with new constexpr rule with C++14: inside constexpr function, you can now use multiple statements, including for loops and control flow.

Here's an example:

constexpr int count5(int start) {
    int acc = 0;

    for (int i = start ; i<start+5 ; ++i) {
        acc += i;
    }

    return acc;
}

constexpr int value = count5(10); // value is 60!

As you can see, we can do many mutation to variable in a constexpr context. The compiler becomes like an interpreter, and as long as the result of the constexpr fonction is consistent and you don't mutate already computed constexpr variables, it may mutate the values during the interpretation.


Basically it is nice when you have to deal with constexpr function.

struct Object {
  constexpr void set(int n);
  int m_n = 0;
};

constexpr Object function() {
   Object a;
   a.set(5);
   return a;
}

constexpr Object a = function();

The idea is to be able to perform compile time initialization within another functions that will be executed at the compile time. It is not done to be applied on constexpr object.

Another things to know is that constexpr member functions are not const member functions since C++14 :).