gpt4 book ai didi

c++ - C++ 中的默认初始化

转载 作者:IT老高 更新时间:2023-10-28 21:50:21 24 4
gpt4 key购买 nike

今天早上我问自己一件事,但我找不到合适的词来“谷歌”:

假设我有:

struct Foo
{
int bar;
};

struct Foo2
{
int bar;
Foo2() {}
};

struct Foo3
{
int bar;
Foo3() : bar(0) {}
};

现在如果我 default 实例化 FooFoo2Foo3:

Foo foo;
Foo2 foo2;
Foo3 foo3;

bar 成员在哪种情况下正确初始化

(好吧,Foo3 显然明确地初始化了它,这里只显示与 Foo2 的区别,所以问题主要是关于前两个。)

谢谢! :)

最佳答案

只有 foo3 会出现在所有上下文中。 foo2 和 foo 将是如果它们是静态持续时间。请注意,Foo 类型的对象在其他上下文中可能初始化为零:

Foo* foo = new Foo(); // will initialize bar to 0
Foo* foox = new Foo; // will not initialize bar to 0

而 Foo2 不会:

Foo2* foo = new Foo2(); // will not initialize bar to 0
Foo2* foox = new Foo2; // will not initialize bar to 0

这个领域很棘手,C++98 和 C++03 之间的措辞发生了变化,IIRC 又是 C++0X,所以我不依赖它。

struct Foo4
{
int bar;
Foo4() : bar() {}
};

bar 也将始终被初始化。

关于c++ - C++ 中的默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6251707/

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