Search code examples
c++copy-elisionreturn-value-optimization

Can copy elision/RVO cause a copy/move from the same object


Let's say I have a function that looks like this:

SomeObject copy_maybe(bool make_new, const SomeObject& def)
{
    if (make_new)
        return SomeObject();
    else
        return def;
}

And I call it like this:

SomeObject obj;
obj = copy_maybe(true, obj);

Without copy elision, this will clearly always result in a copy to obj from a temporary created in copy_maybe. However, with copy elision/RVO, is it possible that the copy will happen from obj to obj?

More specifically, under these (or similar) conditions, is it possible in a copy operator (void operator=(SomeObject const &other)) that this and &other will be the same due to copy elision?

I created a test on Ideone, and it returns separate addresses, but I just want to make sure that this behavior is defined by the spec.


Solution

  • However, with copy elision/RVO, is it possible that the copy will happen from obj to obj?

    No. Copy elison/RVO is used in the process of initializing a variable. Since you already initialized obj using SomeObject obj; you wont get any optimization. The copy assignment operator will be called and the obj from the call site will be assigned the value of the obj from the function.

    If you had

    SomeObject obj = copy_maybe(true, obj);
    

    Then yes, copy elison can (will in C++17) come into play.


    Do note that calling

    SomeObject obj = copy_maybe(false, obj);
    

    Will leave obj in an indeterminate state as it would be the same as

    SomeObject obj = obj;