Return value of non-initialized reference_wrapper

545 Views Asked by At

Where does reference_wrapper point to when I resize() the vector below? Is this an undefined behavior? What should I do for safety?

std::vector < std::reference_wrapper <int> > vec;
vec.resize(10);
2

There are 2 best solutions below

0
On BEST ANSWER

Your code doesn't compile, because reference_wrapper doesn't have a default constructor.

error: no matching function for call to ‘std::reference_wrapper<int>::reference_wrapper()’
0
On

vector<T>::resize(size_type) requires that the T be default constructible, and reference_wrapper isn't, so your code doesn't compile as is.

But presumably, you're asking what happens to the reference_wrapper objects when the vector reallocates storage as necessary. Nothing special, they will continue referring to the object they were originally referring to.

Live demo