Is the following std::vector code valid?

c++, stdvector

Solution

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

Problem

``` 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?

Original source