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

问题描述

我今天早上问自己的东西,我找不到正确的google字样:

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

现在如果我默认实例化 Foo Foo2 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

那个区域很棘手, 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 ++中的默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:02