dimanche 19 juillet 2015

How to return a member of a local object

Consider the following code:

struct Bar
{
    Foo bigData;
    void workOnBigData() { /*...*/ }
}

Foo getBigData()
{
    Bar b;
    b.workOnBigData();
    return b.bigData;
}

What is the best way to implement getBigData() in terms of copy ellision / move semantics? In this implementation the compiler seems not to be allowed to move bigData. I tested the following functions:

Foo f()
{
    Foo foo;
    return foo;  // RVO
}

Foo g()
{
    Bar b;
    return b.bigData;  // Copy
}

Foo h()
{
    Bar b;
    auto r = move(b.bigData);
    return r;  // Move
}

Can you explain the results from these implementations and show the most effective way to return a member of a local object.

Aucun commentaire:

Enregistrer un commentaire