最近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)和 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 标志将错误降级为警告。
关于c++ - 为什么 gcc 允许 const 对象没有用户声明的默认构造函数但不允许 clang?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077807/