gpt4 book ai didi

c++ - vector 中的结构成员是否在 C++ 中初始化为零?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:57 25 4
gpt4 key购买 nike

在 C++ 中,当我有一个像这样的结构时

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

然后我制作一个 vector

std::vector<myStruct> myVector;

然后我调整 vector 的大小

myVector.resize(10);

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

最佳答案

在这种特殊情况下,答案是,因为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

对于正常情况,答案将是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
};

关于c++ - vector 中的结构成员是否在 C++ 中初始化为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25198405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com