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

c – 为什么gcc允许一个const对象没有用户声明的默认构造函数,但

发布时间:2020-12-16 05:34:26 所属栏目:百科 来源:网络整理
导读:最近 Why does a const object requires a user-provided default constructor?被标记为 Why does C++ require a user-provided default constructor to default-construct a const object?的副本.我使用 coliru和 rextexter来测试各种版本的gcc(g -4.7,g -4
最近 Why does a const object requires a user-provided default constructor?被标记为 Why does C++ require a user-provided default constructor to default-construct a const object?的副本.我使用 coliru和 rextexter来测试各种版本的gcc(g -4.7,g -4.8,g -4.9)和cl(3.4和3.5),看看是否在较新版本的编译器中引入了行为.这里我们有两个测试用例,分别从两个问题中提取出来:
class A {
public:
    void f() {}

};

int main()
{
    A a;       // OK
    const A b; // ERROR

    a.f();
    return 0;
}

和:

struct B{
  B():x(42){}
  int doSomeStuff() const{return x;}
  int x;
};

struct A{
  A(){}//other than "because the standard says so",why is this line required?

  B b;//not required for this example,just to illustrate
      //how this situation isn't totally useless
};

int main(){
  const A a;
}

俚语错误与:

error: default initialization of an object of const type 'const A' requires a user-provided default constructor
  A const a;
          ^

预期但不是gcc,也不是MSVC.我想也许我可能会疯了,因为标准引用清楚地说:

第8.5节

6 To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9),the default constructor
for T is called (and the initialization is ill-formed if T has no
accessible default constructor);

[…]

If a program calls for the
default initialization of an object of a const-qualified type T,T
shall be a class type with a user-provided default constructor.

11 If no initializer is specified for an object,the object is
default-initialized; […]

第二个问题中出现的非POD语言似乎从n3337中缺失,所以也许我错过了可能已经改变的内容.这是一个bug,重复还是我错过了什么?

解决方法

该规范目前需要用户提供的默认构造函数,但是似乎GCC正在基于 DR 253实现一个更改,它表示如果所有子对象都将在没有用户提供默认构造函数的情况下被初始化,那么不需要用户提供的默认构造函数.

这种变化只是草案状态,尚未被接受,不属于标准.所以我认为这是GCC开发人员的意图,但我不知道这是否符合一个延伸.

以下是导致GCC产生错误的第一个示例的更改:

class A {
public:
    void f() {}

    int i;
};

int main()
{
    A a;       // OK
    const A b; // ERROR

    a.f();
    return 0;
}

请注意,gcc将错误降级为带有-fpermissive标志的警告.

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=42844

(编辑:李大同)

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

    推荐文章
      热点阅读