为什么构造函数的定义会产生不同的值
Why does the definition of constructor make different value
我正在测试下面的代码片段:
#include <iostream>
struct foo
{
foo() {}
int a;
};
struct bar
{
bar();
int b;
};
bar::bar() = default;
int main()
{
foo f{};
bar b{};
std::cout << f.a << '\t' << b.b << std::endl;
}
输出为0 21946
。
好吧,对象 f
似乎是用零初始化初始化的,但对象 b
是用默认初始化初始化的。 int
的默认初始化是一个随机数,这就是为什么我得到 21946
.
为什么我在这里得到两种不同的初始化?
我知道静态存储持续时间的变量可以用零初始化来初始化,它放在.bss
段,这是一种静态初始化。但是 foo f{}
显然是一种动态初始化。为什么 f
初始化为零初始化,而不是默认初始化?为什么编译器会产生两种不同的行为?
来自cppreference:
Defaulted default constructor outside of class definition (the class must contain a declaration (1)). Such constructor is treated as user-provided
因此,none 个语句是 value-initializations。
两者都是默认初始化,因为它们都有用户提供的构造函数。并且非静态数据成员的值未初始化(可以包含任意数字,包括零)
要对默认构造函数的情况进行值初始化,请使用 in-class 声明:
struct bar
{
bar() = default;
int b;
};
我正在测试下面的代码片段:
#include <iostream>
struct foo
{
foo() {}
int a;
};
struct bar
{
bar();
int b;
};
bar::bar() = default;
int main()
{
foo f{};
bar b{};
std::cout << f.a << '\t' << b.b << std::endl;
}
输出为0 21946
。
好吧,对象 f
似乎是用零初始化初始化的,但对象 b
是用默认初始化初始化的。 int
的默认初始化是一个随机数,这就是为什么我得到 21946
.
为什么我在这里得到两种不同的初始化?
我知道静态存储持续时间的变量可以用零初始化来初始化,它放在.bss
段,这是一种静态初始化。但是 foo f{}
显然是一种动态初始化。为什么 f
初始化为零初始化,而不是默认初始化?为什么编译器会产生两种不同的行为?
来自cppreference:
Defaulted default constructor outside of class definition (the class must contain a declaration (1)). Such constructor is treated as user-provided
因此,none 个语句是 value-initializations。
两者都是默认初始化,因为它们都有用户提供的构造函数。并且非静态数据成员的值未初始化(可以包含任意数字,包括零)
要对默认构造函数的情况进行值初始化,请使用 in-class 声明:
struct bar
{
bar() = default;
int b;
};