In C++14 can a constexpr member change a data memb

2019-04-09 18:22发布

问题:

In C++14, since constexpr are not implicitly const anymore, can a constexpr member function modify a data member of a class:

struct myclass
{
    int member;
    constexpr myclass(int input): member(input) {}
    constexpr void f() {member = 42;} // Is it allowed?
};

回答1:

Yes they are, I believe this change started with proposal N3598: constexpr member functions and implicit const and eventually became part of N3652: Relaxing constraints on constexpr functions which changed section 7.1.5 paragraph 3 what is allowed in the function body from a white-list:

its function-body shall be = delete, = default, or a compound-statement that contains only

  • null statements,
  • static_assert-declarations
  • typedef declarations and alias-declarations that do not define classes or enumerations,
  • using-declarations,
  • using-directives,
  • and exactly one return statement;

to a black-list:

its function-body shall be = delete, = default, or a compound-statement that does not contain

  • an asm-definition,
  • a goto statement,
  • a try-block, or
  • a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed.

and also added the following notes to section C.3.3 Clause 7: declarations:

Change: constexpr non-static member functions are not implicitly const member functions.

Rationale: Necessary to allow constexpr member functions to mutate the object.

Effect on original feature: Valid C++ 2011 code may fail to compile in this International Standard. For example, the following code is valid in C++ 2011 but invalid in this International Standard because it declares the same member function twice with different return types:

struct S {
 constexpr const int &f();
 int &f();
};


回答2:

As far as I can tell, yes. The restrictions are, from [dcl.constexpr]:

The definition of a constexpr function shall satisfy the following constraints:
— it shall not be virtual (10.3);
— its return type shall be a literal type;
— each of its parameter types shall be a literal type;
— its function-body shall be = delete, = default, or a compound-statement that does not contain

  • an asm-definition,
  • a goto statement,
  • a try-block, or
  • a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed.

The function meets all those requirements.