gpt4 book ai didi

c++ - 类常量对象的定义

转载 作者:搜寻专家 更新时间:2023-10-31 00:02:21 27 4
gpt4 key购买 nike

有这样的代码:

class MojaKlasa{
public:
};

int main()
{
const MojaKlasa a;

return 0;
}

编译器错误是:

error: uninitialized const ‘a’

但是在 MojaKlasa 类修改之后:

class MojaKlasa{
public:
MojaKlasa(){}
};

一切正常。默认构造函数应由 C++ 自动定义 - 为什么在这种情况下不这样做而必须显式定义默认构造函数?

最佳答案

草案 n3290 (C++0X) 在 §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 T is an array type, each element is default-initialized;
— otherwise, no initialization is performed.
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.

所以你实际上需要一个用户定义的构造函数,编译器生成的构造函数是不够的。

顺便说一句,clang++ 对此有很好的诊断:

$ clang++ -std=c++0x -pedantic -Wall t.cpp
t.cpp:7:19: error: default initialization of an object of const type
'const MojaKlasa' requires a user-provided default constructor
const MojaKlasa a;
^
1 error generated.

对于C++03,写法如下(§8.5/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 non-static object, the object and its subobjects, if any, have an indeterminate initial value ; if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

这解释了为什么是这样的。你有一个你没有初始化的 POD 类型,所以它的成员有一个“不确定”的值。由于您声明的对象是 const,因此您无法为其字段赋值,因此您留下了一个无法为其赋值的 POD,并且您无法从其中任何一个读取(将是未定义的行为)。不是很有用。

关于c++ - 类常量对象的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com