Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the following std::vector code valid?

Tags:

c++

stdvector

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?

Is the above code safe?

like image 277
anon Avatar asked Dec 23 '22 05:12

anon


1 Answers

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).

like image 196
Johannes Schaub - litb Avatar answered Jan 21 '23 05:01

Johannes Schaub - litb