我对c++初始化变量的方式感到非常困惑。如果有区别,它们之间有什么区别:
int i; // does this make i uninitialized?
int i{}; // does this make i = 0?
std::array<int, 3> a; // is a all zeros or all uninitialized?
std::array<int, 3> a{}; // same as above?
感谢您的澄清
发布于 2021-01-01 18:32:26
int i; // does this make i uninitialized?
是,如果是在局部作用域而不是全局作用域。
int i{}; // does this make i = 0?
是的,一直都是。
std::array<int, 3> a; // is a all zeros or all uninitialized?
如果在局部作用域中未初始化,但在全局作用域中归零,即与您的第一个问题相同。
std::array<int, 3> a{}; // same as above?
所有值都是默认初始化的,即所有三个元素都被置零。
发布于 2021-01-01 18:28:21
当您声明一个变量而没有用值初始化它时,它是未初始化的(它包含以前存储在该地址中的数据)。它还取决于范围和其他因素来确定其初始值。与int i{};
中使用的{}
类似,它调用其构造函数,该构造函数默认将内存初始化为默认值。
所有的数据结构都是一样的(除了那些删除了构造器的数据结构)。
发布于 2021-01-01 18:38:39
我想补充上一个答案,当你像这个{}
一样初始化变量时,它会阻止类型的缩小。例如
int x = 4.5 // It will narrowed to 4
int y{4.5} //it will not compile
https://stackoverflow.com/questions/65528864
复制相似问题