gpt4 book ai didi

c++ - C++11 中 ConstExpr 对象中的可变成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:51 24 4
gpt4 key购买 nike

在 C++14 标准 (ISO/IEC 14882:2014) 中,“non-mutable”这个词被添加到第 5.19 节第 2 段(强调我的):

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • [...]
  • an lvalue-to-rvalue conversion (4.1) unless it is applied to
    • [...]
    • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or

因此,这段代码在 C++14 中是不正确的:

class A {
public:
mutable int x;
};

int main(){

constexpr A a = {1};
constexpr int y = a.x;

return 0;
}

但是,它在 C++11 中是否正确?

这是缺陷报告 (CD3) 1405他们建议在其中添加 non-mutable:

Currently, literal class types can have mutable members. It is not clear whether that poses any particular problems with constexpr objects and constant expressions, and if so, what should be done about it.

所以我会说这是正确的 C++11 代码。尽管如此,我尝试使用 -std=c++11 的 Clang 和 GCC,并且都输出了一个错误,指出常量表达式中不允许使用可变变量。但是这个约束是在 C++14 中添加的,而不是在 C++11 中。

有谁知道该代码在 C++11 中是否正确?

另请参阅缺陷报告 (CD3) 1428 .

最佳答案

这是 C++11 缺陷报告,那么 C++11 需要修复。只有那些具有 DR、accepted、DRWP 和 WP 状态的问题才不是 C++ 国际标准的一部分。

符合 C++11 的编译器必须实现该 DR。

比如这对例子因为DR 1579而改变了:

此示例取自:Why this C++ program gives different output in C++11 & C++14 compilers

关于c++ - C++11 中 ConstExpr 对象中的可变成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848766/

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