In c++11, can a virtual function return a large value efficiently with move semantics?
-
07-07-2021 - |
Question
Normally, this would be optimised to not involve copying the large value (since a std::vector
has move semantics enabled):
std::vector<int> makeABigThing(){
std::vector<int> large_thing(1000, 0);
return large_thing;
}
Can this also be optimised in the same way if the function is a virtual method:
struct Foo{
virtual std::vector<int> makeABigThing(){
std::vector<int> large_thing(1000, 0);
return large_thing;
}
};
i.e., do move semantics work with even when the called function is selected at runtime?
La solution
Whether the function is static or dynamically resolved does not affect the possibility of moving the result.
Autres conseils
virtual
doesn't change anything compared to not. The compiler still knows the return type in compile time. In fact this is (almost*) guaranteed to use vector's move semantics.
*It could elide it altogether via NRVO
This optimization is called copy elision (http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/) and it is prior to c++11. Both move semantics and copy elision are the same kind of solution and both are part of the standard but copy elision is implemented by the compiler while move semantics offers the control of this optimization by the programmer.
The behaviour should be the same, virtual or not.