C++ 中的默认初始化

Default initialization in C++(C++ 中的默认初始化)

本文介绍了C++ 中的默认初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was asking myself something this morning, and I can't find the words to properly "google" for it:

假设我有:

struct Foo
{
  int bar;
};

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

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

现在如果我 default 实例化 FooFoo2Foo3:

Now if I default instantiate Foo, Foo2 and Foo3:

Foo foo;
Foo2 foo2;
Foo3 foo3;

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

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

(Well Foo3 obviously explicitely initialize it and is only showed here to explicit the difference with Foo2 so the question is mainly about the first two.)

谢谢!:)

推荐答案

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

Only foo3 will be in all contexts. foo2 and foo will be if they are of static duration. Note that objects of type Foo may be zero initialized in other contexts:

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,所以我不依赖它.

that area is tricky, the wording as changed between C++98 and C++03 and, IIRC, again with C++0X, so I'd not depend on it.

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

bar 也将始终被初始化.

bar will always be initialized as well.

这篇关于C++ 中的默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 中的默认初始化

基础教程推荐