c++ - 在什么情况下,c++ 会将变量初始化为零?

标签 c++ initialization

<分区>

每个变量在使用前都应该被正确定义和初始化(给它赋值)。然而,在某些情况下,C++ 会将变量设置为默认值零。就像下面的案例。

class A{
    ...
    static int val;
    ...};

//int val = 10; //This is the usual definition.
int val;//Definition without assigning a value.
...
A a;  //a class A object
std::cout<<a.val;

结果将为零。显然,编译器将变量 a.val 初始化为零。我很好奇他们一般什么时候会这样做?

最佳答案

http://en.cppreference.com/w/cpp/language/zero_initialization

Zero initialization is performed in the following situations:

  1. For every named variable with static or thread-local storage duration, before any other initialization.
  2. As part of value-initialization (i.e. with an empty pair of parentheses or braces) sequence for non-class types and for members of value-initialized class types that have no constructors.
  3. When a character array is initialized with a string literal that is too short, the remainder of the array is zero-initialized.

关于c++ - 在什么情况下,c++ 会将变量初始化为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20403041/

相关文章:

c++ - C++按有效位查找范围ip地址

c++ - 从基本指针的源容器构造一个派生指针的容器

c++ - 获取已安装的应用程序列表

c++ - 从 4.7 开始的 g++ 会忽略大括号内的名称大小写 #include

c++ - 静态初始化 C++,未设置值

emacs - 更改 .emacs 文件的位置

ruby - 我是否必须初始化类的所有成员变量?

c++ - std::string 类成员应该是指针吗?

swift - 我可以在协议(protocol)中有一个初始化函数吗?

initialization - 如何决定使用哪种模式进行 'kaiming_normal' 初始化