Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c++11, can a virtual function return a large value efficiently with move semantics?

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?

like image 892
James Avatar asked Oct 16 '12 20:10

James


People also ask

Are virtual functions bad for performance?

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.

Are virtual functions faster?

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.

What is the advantage of virtual function in c++?

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.

Where does the overhead in a C++ virtual function come from?

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.


2 Answers

Whether the function is static or dynamically resolved does not affect the possibility of moving the result.

like image 144
David Rodríguez - dribeas Avatar answered Oct 17 '22 19:10

David Rodríguez - dribeas


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

like image 4
David Avatar answered Oct 17 '22 21:10

David