Question

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?

Was it helpful?

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

OTHER TIPS

You should use vec.resize(100) if you want to index-in right away.

vec[50] is only safe if 50 < vec.size(). reserve() doesn't change the size of a vector, but resize() does and constructs the contained type.

It won't work. While the container has 100 elements reserved, it still has 0 elements.

You need to insert elements in order to access that portion of memory. Like Jon-Eric said, resize() is the way to go.

std::vector::reserve(100) will claim 100*sizeof(Foo) of free memory, so that further insertion to a vector will not do a memory allocation until 100*sizeof(foo) is full, but accessing the element of that vector will give indeterministic content of that element, since its only claim the memory not allocate it.

Before you can use operator[] to access 50th element you should either call resize, push_back() something 50 times or use std::fill_n algorithm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top