加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11中ConstExpr对象中的可变成员

发布时间:2020-12-16 07:20:28 所属栏目:百科 来源:网络整理
导读:在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 t
在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,这对示例发生了变化:

> gcc 6.1.0
> gcc 4.9.3

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读