C++ 我是否必须初始化简单的类成员变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3053057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:54:22  来源:igfitidea点击:

Do I have to initialize simple class member variables?

c++classvariablesinitialization

提问by Frank

Quick beginner's question:

快速初学者的问题:

Do I haveto initialize simple class member variables, or are they guaranteed to get assigned their default values in any case?

是否必须初始化简单的类成员变量,还是保证在任何情况下都能为其分配默认值?

Example:

例子:

class Foo {
  int i;
  // is i==0 or do I need the following line for that?
  Foo() : i(0) {}
};

Thanks!

谢谢!

回答by utnapistim

Do I have to initialize simple class member variables,

我是否必须初始化简单的类成员变量,

No, you don't haveto initialize the member variables. If you do not initialize them though, do not assume they will have any value.

不,你不会初始化成员变量。如果你不初始化它们,不要假设它们会有任何价值。

If you make a test program and check in debugger how the values are initialized you may see them initialized as zeros, but that is not guaranteed. The values get initialized to whatever is in memory on the stack at that location.

如果您制作一个测试程序并在调试器中检查这些值是如何初始化的,您可能会看到它们被初始化为零,但这并不能保证。这些值被初始化为该位置堆栈上内存中的任何内容。

or are they guaranteed to get assigned their default values in any case?

或者他们是否保证在任何情况下都能获得默认值?

They are not guaranteed to get assigned any value. If you have member objects the default constructors will be called for them, but for POD types there is no default initialization.

不保证它们会被分配任何值。如果您有成员对象,则会为它们调用默认构造函数,但对于 POD 类型,则没有默认初始化。

Even though you don't have to do it, it is good practice to initialize allmembers of your class (to avoid hard to find errors and to have an explicit representation of the initializations / constructor calls).

即使您不必这样做,初始化类的所有成员也是一种很好的做法(以避免难以发现错误并明确表示初始化/构造函数调用)。

回答by AJ.

Yes, that is necessary. Your object will be allocated either on the stack or on the heap. You have no way of knowing what values that memory contains, and the runtime does not guarantee zeroing this for you, so you mustinitialise the variable.

是的,这是必要的。您的对象将在堆栈​​或堆上分配。您无法知道内存包含哪些值,并且运行时不保证将其归零,因此您必须初始化该变量。

回答by Bj?rn Pollex

Read this. This page is also helpful for many other questions you may have down the stone road of learning C++.

这个。此页面也对您在学习 C++ 的石路中可能遇到的许多其他问题有所帮助。

In general, you don't have to, but you should. Relying on default values can really come back hard on you. Also this makes the code better to understand for others. Keep in mind that the initialization list does not affect the order in which members are initialized, that is determined by the order they are declared in the class.

一般来说,您不必这样做,但您应该这样做。依赖默认值真的会让你很难受。这也使代码更易于其他人理解。请记住,初始化列表不影响成员初始化的顺序,这是由它们在类中声明的顺序决定的。