【发布时间】:2014-11-22 13:00:24
【问题描述】:
最近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 默认初始化 T 类型的对象意味着:
——如果 T 是一个(可能是 cv 限定的)类类型(第 9 条),则默认构造函数 for T 被调用(如果 T 没有 可访问的默认构造函数);
[...]
如果一个程序调用 const 限定类型 T, T 的对象的默认初始化 应该是具有用户提供的默认构造函数的类类型。
11 如果没有为对象指定初始化器,则该对象为 默认初始化; [...]
n3337 中似乎缺少第二个问题中出现的非 POD 语言,所以也许我遗漏了一些可能已经改变的东西。这是错误、重复还是我遗漏了什么?
【问题讨论】: