C++中的变量初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2218254/
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-27 22:35:44  来源:igfitidea点击:

Variable initialization in C++

c++variablesinitialization

提问by skydoor

My understanding is that an intvariable will be initialized to 0automatically; however, it is not. The code below prints a random value.

我的理解是一个int变量会被0自动初始化;然而,事实并非如此。下面的代码打印一个随机值。

int main () 
{   
    int a[10];
    int i;
    cout << i << endl;
    for(int i = 0; i < 10; i++)
        cout << a[i] << " ";
    return 0;
}
  • What rules, if any, apply to initialization?
  • Specifically, under what conditions are variables initialized automatically?
  • 哪些规则(如果有)适用于初始化?
  • 具体来说,在什么条件下变量会自动初始化?

回答by AndiDog

It will be automatically initialized if

它将自动初始化,如果

  • it's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance;
  • you use array initializer syntax, e.g. int a[10] = {}(all zeroed) or int a[10] = {1,2};(all zeroed except the first two items: a[0] == 1and a[1] == 2)
  • same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here)
  • it's a global/extern variable
  • the variable is defined static(no matter if inside a function or in global/namespace scope) - thanks Jerry
  • 它是一个类/结构实例,其中默认构造函数初始化所有原始类型;喜欢MyClass instance;
  • 您使用数组初始值设定项语法,例如int a[10] = {}(全部归零)或int a[10] = {1,2};(除前两项外全部归零:a[0] == 1a[1] == 2
  • 同样适用于非聚合类/结构,例如 MyClass instance = {}; (更多信息可以在这里找到)
  • 这是一个全局/外部变量
  • 变量已定义static(无论是在函数内还是在全局/命名空间范围内) -感谢 Jerry

Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.

永远不要相信一个普通类型(int、long、...)的变量会被自动初始化!它可能会发生在像 C# 这样的语言中,但不会发生在 C 和 C++ 中。

回答by Vivin Paliath

intdoesn't initialize to zero. When you say int i;, all you're doing is reserving space for an integer. The value at that location is not initialized. That's only done with you say int i = 0;(or int i = 5;in which case the value is initialized to 5). Eitherway, it's good practice to initialize a variable to some known value. Otherwise, iholds whatever random value was at that memory location when space was reserved for it. This is why the coutprints out a random value.

int不会初始化为零。当您说 时int i;,您所做的就是为整数保留空间。该位置的值未初始化。这只是你说的int i = 0;(或者int i = 5;在这种情况下,值被初始化为 5)。无论哪种方式,将变量初始化为某个已知值都是很好的做法。否则,i当为它保留空间时,保存该内存位置的任何随机值。这就是为什么cout打印出一个随机值。

Default values depend on the implementation of the language. Some languages will initialize it to some "sane" value (like 0 perhaps). As a rule of thumb, I always initialize a variable to some sensible value (unless I know that I am going to initialize it to something else for surebefore I use it). As I mentioned before, it's unwise to assumethat the value is going to be something sane. It may or may not be (depending on the language, or the implementation of the interpreter/compiler for that language).

默认值取决于语言的实现。某些语言会将其初始化为某个“正常”值(例如 0)。根据经验,我总是将一个变量初始化为某个合理的值(除非我知道在使用它之前我肯定会将它初始化为其他)。正如我之前提到的,假设价值将是理智的东西是不明智的。它可能是也可能不是(取决于语言,或该语言的解释器/编译器的实现)。

回答by Nick Presta

See section 4.9.5 Initialization of The C++ Programming Language.

请参阅第 4.9.5 节 C++ 编程语言的初始化。

Depending on whether your variable is local, static, user-defined or const default initialization can happen.

根据您的变量是本地的、静态的、用户定义的还是 const 默认初始化,可能会发生。

Because you're using POD (Plain Old Datatypes), the auto variable is not initialized to any default value.

因为您使用的是 POD(普通旧数据类型),所以 auto 变量不会初始化为任何默认值。

回答by Logan Capaldo

To force initialization of a POD (which intis), you can use copy initializer syntax:

要强制初始化 POD(即int),您可以使用复制初始化语法:

#include <iostream>

int main() {
  int i = int();
  int j;

  std::cout << "i: " << i << std::endl;
  // warning: undefined behavior
  std::cout << "j: " << j << std::endl;
}

This is falls under "only pay for what you use". If you are going to subsequently assign a value to the variable, or possibly not use it at all, there's no reason to do the work of initializing it. To get that, you have to explicitly ask that that work be done.

这属于“只为你使用的东西付费”。如果您打算随后为变量赋值,或者可能根本不使用它,则没有理由进行初始化工作。要做到这一点,您必须明确要求完成这项工作。

回答by Will

This post says it best: http://www.velocityreviews.com/forums/showpost.php?p=1528247&postcount=10

这篇文章说得最好:http: //www.velocityreviews.com/forums/showpost.php?p=1528247&postcount=10

There's no "default" constructor for non-class types, but there is default (zero) initialization. Unfortunately, for braindead compatibility with C, the default initialization is NOT done for POD types in the following circumstances:

Naked (i.e., declared without initializers) variables local to a class or function.

dynamically allocated instances.

However, in other places (notably static variables) and in the case of anything given the empty initializer paramters (when that is valid), gets the default (zero) initialization.

非类类型没有“默认”构造函数,但有默认(零)初始化。不幸的是,为了与 C 兼容,在以下情况下不会对 POD 类型进行默认初始化:

类或函数的局部变量(即,没有初始化器声明)局部变量。

动态分配的实例。

但是,在其他地方(特别是静态变量)和任何给定空的初始化参数的情况下(当它有效时),获得默认(零)初始化。

回答by Jakob Borg

In C++, automatic variables are undefined until they are explicitly given a value. Perhaps you are thinking of C# or other .Net languages, or Java.

在 C++ 中,自动变量在被明确赋予一个值之前是未定义的。也许您正在考虑 C# 或其他 .Net 语言,或者 Java。

回答by t. fochtman

Different operating systems ( i.e. OS X vs. Ubuntu Linux ) will react differently to uninitialized versus initialized variables in C++. In my experience, the OS X version of gcc will compile and print out 2 for both versions of the code below. Where as if I'm working on an Ubuntu Linux machine the first code block will print out whatever happened to be at the memory location the variable references ( + 2 after the loop ).

不同的操作系统(即 OS X 与 Ubuntu Linux)对 C++ 中未初始化变量与已初始化变量的反应不同。根据我的经验,OS X 版本的 gcc 将为以下两个版本的代码编译并打印出 2。就像我在 Ubuntu Linux 机器上工作一样,第一个代码块将打印出变量引用的内存位置发生的任何事情(循环后的 + 2)。

    int c;

    for( int i = 0; i < 3; i++ )
    {
        c++;
    }

    cout << c << endl; 

Where as, they will all give you the same results for:

其中,它们都会为您提供相同的结果:

    int c = 0;

    for( int i = 0; i < 3; i++ )
    {
        c++;
    }

    cout << c << endl; 

回答by Anon.

Local variables aren't initialized unless you do it yourself. What you're seeing is whatever garbage was on the stack before your method was called.

除非您自己初始化,否则不会初始化局部变量。您看到的是在调用您的方法之前堆栈上的任何垃圾。

回答by eel ghEEz

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value.

如果没有为对象指定初始化程序,则该对象是默认初始化的;如果不进行初始化,具有自动或动态存储持续时间的对象具有不确定的值。

Par. 8.5, section 11 of a recent C++0x draft N3092.pdf,

标准杆。8.5,最近的 C++0x 草案 N3092.pdf 的第 11 节,

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/

回答by phlip

Although your recent discovery may be unwelcome (because you may need to initialise some variables other languages would have taken care of), it can mean fewer cpu cycles, and thus faster code.

尽管您最近的发现可能不受欢迎(因为您可能需要初始化其他语言会处理的一些变量),但它可能意味着更少的 cpu 周期,从而更快地编写代码。