gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:35 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com