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?
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::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.
std::uninitialized_fill_n is no better than what he's doing.generate with a simple function is no different from fill_n which isn't as close to what we want as uninitialized_fill_n. No generic algorithm will work here because STL algos change sequences, not containers. A back_insert_iterator would be a roundabout way of doing this, if you are set on using <algorithm>.
attooperator[]. Although semantically identical and a bit longer to write, it does have the so-calledbound-checkingfeature. I would never consider anything that write outside the boundaries assafe...