向量中的结构成员是否在C++中初始化为零?

Bra*_*sen 4 c++ struct vector

在C++中,当我有一个类似的结构

struct myStruct
{
  int i;
  bool b;
  MyClass *myobj;
};
Run Code Online (Sandbox Code Playgroud)

然后我做了一个这样的矢量

std::vector<myStruct> myVector;
Run Code Online (Sandbox Code Playgroud)

我用它来调整矢量大小

myVector.resize(10);
Run Code Online (Sandbox Code Playgroud)

struct的成员是否会用零(包括指针)初始化?我可以不假设结构成员中可能存在随机数据吗?

her*_*tao 5

在这种特殊情况下,答案是肯定的,因为它std::vector::resize()的属性:

If the current size is less than count, additional elements are appended and initialized with copies of value.      (until C++11)

If the current size is less than count,  (since C++11)
    1) additional value-initialized elements are appended
    2) additional copies of value are appended
Run Code Online (Sandbox Code Playgroud)

对于正常情况,答案将为NO,例如myStruct s,这将使它们(s.i, s.bool, s.myobj)具有不确定的值.

如果您仍希望按预期初始化它们,请为结构创建一个构造函数:

struct myStruct {
    int i;
    bool b;
    MyClass *myobj;

    myStruct():i(0),b(false),myobj(NULL) { }  // <- set them here by default
};
Run Code Online (Sandbox Code Playgroud)