微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

最近 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?的副本.我使用 colirurextexter来测试各种版本的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

原文地址:https://www.jb51.cc/c/114428.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐