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

3

5

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?

Brisson answered 16/10, 2012 at 20:47 Comment(0)
U
7

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

Untruthful answered 16/10, 2012 at 20:55 Comment(0)
D
4

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

Delladelle answered 16/10, 2012 at 20:56 Comment(1)
To put it another way, a typical call to makeABigThing() IS guaranteed to not involve a vector copy constructor.Remorseless
N
0

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.

Neurasthenic answered 16/10, 2012 at 21:1 Comment(2)
Copy elision is a part of the Standard too (it specifies in exactly what situations the elision is optional vs. not allowed).Remorseless
@aschepler: Yeah, but what I was trying to say is: you can control (or try to) the behaviour on move semantics (through std::move, std::forward ...). On the other side, copy elision is beyond our control. ThanksNeurasthenic

© 2022 - 2024 — McMap. All rights reserved.