Vector return copy

Would the follow produce two copies of a vector? One right before the return and one right after? If so, is there a way to do this with only one copy?

Thanks!


1
2
3
4
5
6
7
8
std::vector<float> SubVector::getSubVector( ) {
  return std::vector<float>(privateVector.begin()+10, privateVector.begin()+20);
}

..........

SubVector largeVector;
std::vector<float> subVec = largeVector.getSubVector();
It depends on the compiler. With optimizations turned on it will probably not create any copies.
Last edited on
I hope someone will be able to confirm, but I think this is the situation where normally (with no optimizations) this code will copy the vector twice, but the standard allows the compiler to optimize one of them away.

(Maybe, if the code can be inlined, then both of them can be optimized)

Try the same thing with you own type, and print something in the copy constructor to see how many copies it makes.
The elements from privateVector.begin()+10 to privateVector.begin()+20 will be copied, once into the new 10-element vector called largeVector.

Both potential copies (copy-initialization of the function return value from the temporary created by the return expression and copy-initialization of largeVector from the temporary returned from the function call) are optimized out unless you can find a compiler from the 80s. Even Visual Studio Debug build has this optimization turned on.
Last edited on
Awesome, is there a place to find common optimizations like this? Also, I've heard/seen of a way to check for things like this after compilation. Do you know of any references for this or what it is called?

Thanks!
what it is called?

It's called copy elision. There are many flavors of it, the two involved here are:
1) Unnamed return value optimization, URVO (often simply "RVO" since back in the 90s it was the only form available)
2) Copy-initialization from a temporary, which I don't think has an acronym.

As for references, I suppose
http://en.cppreference.com/w/cpp/language/copy_elision
and the ever-popular
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Topic archived. No new replies allowed.