Possible Duplicate:
uninitialized const
我知道需要初始化一个 const 对象。
所以对于下面的代码,
class sample
{};
int main()
{
const sample obj;
return 0;
}
编译器会报错,因为 const 对象 obj
没有初始化。
但是当我使用默认构造函数修改代码(如下所示)时,编译器不会抛出任何错误。
class sample
{
public:
sample() { }
};
int main()
{
const sample obj;
return 0;
}
新添加的默认ctor做了什么让编译器满意的事情?
新添加的默认ctor做了什么让编译器满意的事情?
因为这是 C++ 标准在使用 const
限定符声明对象时强加的要求。
引用:
C++03 8.5 初始化器 8 声明器
§9:
If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value90); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.