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?
Virtual functions are slow when you have a cache miss looking them up. As we'll see through benchmarks, they can be very slow. They can also be very fast when used carefully — to the point where it's impossible to measure the overhead.
Objects of classes with virtual functions have only a small space-overhead compared to those that don't have virtual functions. Calling a virtual function is fast — almost as fast as calling a non-virtual function. You don't get any additional per-call overhead no matter how deep the inheritance gets.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. Functions are declared with a virtual keyword in base class. The resolving of function call is done at runtime.
Most overhead of virtual functions comes from small functions, they cost more to call than to execute. Also, the compiler is really good at optimizing small virtual functions. Keep objects in the vector sorted by type.
Whether the function is static or dynamically resolved does not affect the possibility of moving the result.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With