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?
};
According to the proposal, an object created within a constexpr expression, can now be changed during the evaluation process - until the evaluation process or the object's lifetime ends.
constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.
const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.
Even though try blocks and inline assembly are allowed in constexpr functions, throwing exceptions or executing the assembly is still disallowed in a constant expression.
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(); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With