-3

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);
Praetorian
  • 106,671
  • 19
  • 240
  • 328
Shibli
  • 5,879
  • 13
  • 62
  • 126

2 Answers2

5

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()’
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

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

Praetorian
  • 106,671
  • 19
  • 240
  • 328