Is the following std :: vector code valid?

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?

+4
source share
5 answers

Not valid. A vector has no elements, so you cannot access any element from them. You just reserved space for 100 items (this means that it ensures that redistribution does not happen until more than 100 items are inserted).

The fact is that you cannot resize a vector without initializing elements (even if initialization is the default).

+7
source

You must use vec.resize(100) if you want to index immediately.

vec[50] is safe if 50 < vec.size() . reserve() does not resize the vector, but resize() does and constructs the contained type.

+4
source

This will not work. While the container contains 100 elements, it still has 0 elements.

You need to insert elements to access this part of the memory. As John Eric said, resize() is the way to go.

0
source

std :: vector :: reserve (100) will require 100 * sizeof (Foo) free memory, so further insertion into the vector will not allocate memory until 100 * sizeof (foo) is filled, but access to the element of this vector will give an indeterminate content of this element, since its only requirement is that memory does not allocate it.

0
source

Before you can use the [] operator to access the 50th item, you must either call resize, push_back () about 50 times, or use the std :: fill_n algorithm.

0
source

Source: https://habr.com/ru/post/1303185/


All Articles