RVO on different compilers when using containers

67 views Asked by At

I have the following code on c++17

template<typename T>
std::vector<T*> getPointerVector(std::vector<T> base) {
  auto out = std::vector<T*>();
  for (auto& t : base) {
      out.push_back(&t);
  }
  return out;
}

As far as i understand RVO should kick in and prevent any copying of the returned vector. However, when i use GCC it all works fine, using msvc it does not and the vector is actually copied. Any explanations? Thanks!

Edit: When I debugged I made sure the reference in memory is the same for the vector inside the function and on the calling side. That is true for gcc 8.3 on debian testing and not true for msvc on visual studio 19.4

1

There are 1 answers

1
Lightness Races in Orbit On

Apparently your version of Visual Studio just doesn't do that.

Or…

When I debugged I made sure the reference in memory is the same for the vector inside the function and on the calling side. That is true for gcc 8.3 on debian testing and not true for msvc on visual studio 19.4

If you're debugging, presumably you're making a debug build, for which optimisations are usually much less fierce. So it could simply be that you turned this off.

It will at least be moving the vector, so there's that.

By the way, every element of the vector you're returning is a dangling pointer. Did you mean to take base by reference? Also, an out.reserve(base.size()) call wouldn't hurt.