在C 14标准(ISO / IEC 14882:2014)中,第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,他们建议添加不可变:
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,接受,DRWP和WP状态的问题不属于C国际标准的一部分.
符合C 11的编译器必须实现该DR.
例如,由于DR 1579,这对示例发生了变化:
此示例取自:Why this C++ program gives different output in C++11 & C++14 compilers