c++ - 为什么 gcc 允许 const 对象没有用户声明的默认构造函数但不允许 clang?

标签 c++ gcc clang

最近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)和 clang(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;
}

clang 错误输出:

 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; [...]

n3337 似乎缺少第二个问题中出现的非 POD 语言,所以我可能遗漏了一些可能已经更改的内容。这是错误、重复还是我遗漏了什么?

最佳答案

该规范目前需要用户提供的默认构造函数,但 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

关于c++ - 为什么 gcc 允许 const 对象没有用户声明的默认构造函数但不允许 clang?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077807/

相关文章:

与 GCC 输出混淆

vim - clang_complete 和 iOS

c++ - 无法在 debian 7 64 位上链接 chromium 嵌入式框架 3

c++ - QT + winId() - 确定句柄类型

c++ - 是否有一种很好的通用方法可以在 ruby​​ 中包装 swig 生成的类?

c++ - GCC 会为运行时保留固定值的算术运算还是编译输出?

C++ 在 unixtime 中获取今年的开始

c++ - 使用 gcc4 优于 gcc34 的好处?

c++ - 神秘的链接器错误 "undefined reference to ` __gxx_personality_v 0'"在 cygwin 中使用 clang

c++ - 从 LLVM 解析树重新生成源代码?