gpt4 book ai didi

c++ - 为什么 C++ 需要用户提供的默认构造函数来默认构造一个 const 对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:28 27 4
gpt4 key购买 nike

C++ 标准(第 8.5 节)说:

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.

为什么?我想不出在这种情况下需要用户提供的构造函数的任何原因。

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;
}

最佳答案

原因是如果类没有自定义构造函数,那么它可以是POD,POD类默认是不初始化的。那么如果你声明一个未初始化的POD的const对象,它有什么用呢?所以我认为标准强制执行此规则,以便该对象实际上有用。

struct POD
{
int i;
};

POD p1; //uninitialized - but don't worry we can assign some value later on!
p1.i = 10; //assign some value later on!

POD p2 = POD(); //initialized

const POD p3 = POD(); //initialized

const POD p4; //uninitialized - error - as we cannot change it later on!

但是,如果您将类(class)设置为非 POD:

struct nonPOD_A
{
nonPOD_A() {} //this makes non-POD
};

nonPOD_A a1; //initialized
const nonPOD_A a2; //initialized

注意 POD 和非 POD 的区别。

用户定义的构造函数是使类成为非 POD 的一种方法。您可以通过多种方式做到这一点。

struct nonPOD_B
{
virtual void f() {} //virtual function make it non-POD
};

nonPOD_B b1; //initialized
const nonPOD_B b2; //initialized

注意 nonPOD_B 没有定义用户定义的构造函数。编译它。它将编译:

然后注释掉虚函数,然后如预期的那样报错:


嗯,我想,你误解了这段话。它首先这样说 (§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; [...]

它谈论非 POD 类可能是 cv 限定的类型。也就是说,如果没有指定初始化器,非 POD 对象将被默认初始化。什么是默认初始化?对于非 POD,规范说 (§8.5/5),

To default-initialize an object of type T means:
— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

它只是谈论 T 的默认构造函数,无论它是用户定义的还是编译器生成的都无关紧要。

如果您清楚这一点,请理解规范接下来的内容 ((§8.5/9),

[...]; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor.

所以这段文字暗示,如果对象是 const-qualified POD 类型,并且没有指定初始化程序(因为 POD 是未默认初始化):

POD p1; //uninitialized - can be useful - hence allowed
const POD p2; //uninitialized - never useful - hence not allowed - error

顺便说一下,this compiles fine ,因为它不是 POD,并且可以默认初始化

关于c++ - 为什么 C++ 需要用户提供的默认构造函数来默认构造一个 const 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077570/

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