现代c ++是否具有默认的初始化值

时间:2014-10-14 17:03:32

标签: c++ initialization

我是c ++的新手,我想学习c ++的最佳实践。我有一个问题,现代c ++编译器会自动为未初始化的变量分配默认值吗?如果是,是否意味着我们不需要为变量分配默认值,或者它取决于系统?

感谢您的帮助和澄清。

3 个答案:

答案 0 :(得分:4)

始终只会初始化静态和全局数据...

int w; // will be 0
static int x; // will be 0

void f() { static int x; /* will be 0 the first time this scope's entered */ }

struct S
{
    int n_;
};

S s_;  // s_.n_ will be 0 as s_ is global

int main()
{
    S s;  // s.n_ will be uninitialised
          // undefined behaviour to read before setting
}

对于任何其他变量,它们必须具有 - 在代码中的某个级别 - 在读取之前进行显式初始化。这可能在声明变量的时候不可见 - 它可能在默认构造函数或赋值中。你也可以像这样进行初始化:

int x{};  // will be 0
int* p = new int{};  // *p will be 0 

答案 1 :(得分:1)

默认初始化在三种情况下执行:
1)当声明具有自动,静态或线程局部存储持续时间的变量时,没有初始化器 2)具有动态存储持续时间的对象是由没有初始化程序的new-expression创建的,或者是由new-expression创建的对象,初始化程序由一对空括号组成(直到C ++ 03)。 /> 3)当构造函数初始化列表中没有提到基类或非静态数据成员并且调用该构造函数时。

更多信息: http://en.cppreference.com/w/cpp/language/default_initialization

答案 2 :(得分:0)

关于编译器将做什么,我认为它更多的是逆,例如:

int x; // still must be inited, will contain random data
if (some_func())
{
   // some devs will do this for "performance" - i.e don't assign a value to x
   x = 2;
}

但如果你写:

int x = 0;
if (some_func())
{
   x = 2;
}

编译器会将其优化为:

int x;
if (some_func())
{
   x = 2; // Yes this code is actually the first example again :)
}

假设x未在函数中的其他位置使用。