Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the compiler elide the following copy?

I'm still a rookie programmer, I know that premature optimization is bad, but I also know that copying huge stuff around is bad, as well.

I've read up on copy elision and it's synonyms but the examples on Wikipedia for example make it seem to me that copy elision can only take place if the object to be returned gets returned at the same time it gets completely constructed.

What about objects like vectors, which usually only make sense when filled with something, when used as a return value. After all, an empty vector could just be instantiated manually.

So, does it also work in a case like this?

bad style for brevity:

vector<foo> bar(string baz)
{
    vector<foo> out;
    for (each letter in baz)
        out.push_back(someTable[letter]);

    return out;
}

int main()
{
     vector<foo> oof = bar("Hello World");
}

I have no real trouble using bar(vector & out, string text), but the above way would look so much better, aesthetically, and for intent.

like image 639
Erius Avatar asked May 26 '11 13:05

Erius


1 Answers

the examples on wikipedia for example make it seem to me that copy elision can only take place if the object to be returned gets returned at the same time it gets completely constructed.

That is misleading (read: wrong). The issue is rather that only one object is returned in all code paths, i.e. that only one construction for the potential return object is happening.

Your code is fine, any modern compiler can elide the copy.

On the other hand, the following code could potentially generate problems:

vector<int> foo() {
    vector<int> a;
    vector<int> b;
    // … fill both.
    bool c;
    std::cin >> c;
    if (c) return a; else return b;
}

Here, the compiler needs to fully construct two distinct objects, and only later decides which of them are returned, hence it has to copy once because it cannot directly construct the returned object in the target memory location.

like image 190
Konrad Rudolph Avatar answered Oct 08 '22 16:10

Konrad Rudolph