c++ - 在 C++14 中,constexpr 成员可以更改数据成员吗?

标签 c++ constants c++14 member constexpr

在 C++14 中,由于 constexpr 不再是隐式 constconstexpr 成员函数是否可以修改类的数据成员:

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

最佳答案

是的,我相信这个变化是从 proposal N3598: constexpr member functions and implicit const 开始的并最终成为 N3652: Relaxing constraints on constexpr functions 的一部分这改变了部分 7.1.5 段落 3 白名单中函数体中允许的内容:

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;

加入黑名单:

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.

并且还在 C.3.3 部分第 7 条:声明中添加了以下注释:

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();
};

关于c++ - 在 C++14 中,constexpr 成员可以更改数据成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699007/

相关文章:

c++ - 如何检查 std::vector 的调整大小是否有适当的内存

c++ - 制作功能 "const"的意图是什么

ios - 为苹果 watch 和 iphone 应用程序创建常量?

c++ - 未初始化的常量

c - C 在外部声明一个非常量变量 'const' 是否合法?

c++ - 为什么 std::atomic 构造函数在 C++14 和 C++17 中的行为不同

C++ 创建通用 std::bind 的 std::packaged_task

c++ - 为什么转换不起作用?

c++ - 确定指向抽象类的指针设置为哪个派生类

c++ - 成员函数中的 decltype(auto) 忽略无效主体,decltype(expr) 失败