And*_* DM 9 c++ scope initialization built-in-types c++11
问:
为什么定义内置型的未初始化的对象内的函数体已经明确的值,而内置类型定义的对象之外的任何功能被初始化为0
或''
?
举个例子:
#include <iostream>
using std::cout; using std::endl;
int ia[10]; /* ia has global scope */
int main()
{
int ia2[10]; /* ia2 has block scope */
for (const auto& i : ia)
cout << i << " "; /* Result: 0 0 0 0 0 0 0 0 0 0 */
cout << endl;
for (const auto& i : ia2)
cout << i << " "; /* Result: 1972896424 2686716 1972303058 8
1972310414 1972310370 1076588592 0 0 0 */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*vin 17
因为C++的一般规则之一就是你不为你不使用的东西买单.
初始化全局对象相对便宜,因为它只在程序启动时发生一次.初始化局部变量会增加每个函数调用的开销,这并不是每个人都想要的.所以决定将locals的初始化设置为可选,与C语言相同.
BTW如果要在函数内初始化数组,可以编写:
int ia2[10] = {0};
Run Code Online (Sandbox Code Playgroud)
或者在C++ 11中:
int ia2[10]{};
Run Code Online (Sandbox Code Playgroud)