Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 456
jpfx1342 Avatar asked Apr 11 '18 17:04

jpfx1342


People also ask

How does copy elision work?

Guaranteed copy elision redefines a number of C++ concepts, such that certain circumstances where copies/moves could be elided don't actually provoke a copy/move at all. The compiler isn't eliding a copy; the standard says that no such copying could ever happen.

What is copy move elision?

C++ Copy Elision Purpose of copy elision Copy elision (sometimes called return value optimization) is an optimization whereby, under certain specific circumstances, a compiler is permitted to avoid the copy or move even though the standard says that it must happen.

How do you avoid copy elision?

GCC provides the -fno-elide-constructors option to disable copy-elision. This option is useful to observe (or not observe) the effects of return value optimization or other optimizations where copies are elided. It is generally not recommended to disable this important optimization.

What are copy elision and return value optimization?

Common forms of copy elision (Named) Return value optimization is a common form of copy elision. It refers to the situation where an object returned by value from a method has its copy elided. The example set forth in the standard illustrates named return value optimization, since the object is named.


1 Answers

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;
like image 173
NathanOliver Avatar answered Sep 20 '22 17:09

NathanOliver