我是 c++ 的新手,我想学习 c++ 的最佳实践。我有一个问题,现代 C++ 编译器是否会自动为未初始化的变量分配默认值?如果是,是否意味着我们不需要为变量分配默认值或它取决于系统?
感谢您的帮助和澄清。
最佳答案
只有静态和全局数据总是被初始化...
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
关于c++ - 现代c++是否会有默认的初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26366278/