本文介绍了以下 std::vector 代码有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
std::vector<Foo> vec;
Foo foo(...);
assert(vec.size() == 0);
vec.reserve(100); // I've reserved 100 elems
vec[50] = foo; // but I haven't initialized any of them
// so am I assigning into uninitialized memory?
上面的代码安全吗?
推荐答案
无效.该向量没有元素,因此您无法访问其中的任何元素.您只是为 100
元素保留了空间(这意味着在插入超过 100 个元素之前不会发生重新分配).
It's not valid. The vector has no elements, so you cannot access any element of them. You just reserved space for 100
elements (which means that it's guaranteed that no reallocation happens until over 100 elements have been inserted).
事实是你不能在不初始化元素的情况下调整向量的大小(即使只是默认初始化).
The fact is that you cannot resize the vector without also initializing the elements (even if just default initializing).
这篇关于以下 std::vector 代码有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!