为什么类型变量;不调用默认 CTR

Why does Type variable; does not call the default ctor?

本文关键字:默认 CTR 调用 类型变量 为什么      更新时间:2023-10-16

让我们假设下面的类Foo。

struct Foo
{
  int i;
  bool j;
};

为什么我从以下行得到不同的结果?

int main(void)
{
    //I thought the default constructor would be called
    Foo foo1;
    cout << foo1.i << " : " << foo1.j << endl; // " 4196352 : 0 " --> ctor not called?
    //if calling the default constructor explicitly
    foo1 = Foo(); 
    cout << foo1.i << " : " << foo1.j << endl; // " 0 : 0" --> ctor called.
}

不应该隐式调用默认 ctor 吗?

根据CPP参考:

如果没有为类类型(结构、类或联合(提供任何类型的用户声明的构造函数,编译器将始终将默认构造函数声明为其类的内联公共成员。

根据C++标准

隐式定义的默认构造函数执行一组 将由用户编写的类执行的类的初始化 该类的默认构造函数,没有 CTOR-nitializer (15.6.2( 和一个空的复合语句

该类有一个简单的默认收缩器,它不初始化类的成员。所以它们有不确定的值。

这种形式的构造者的呼叫

Foo()

值初始化数据成员。对于基本类型,它意味着零初始化。