RMP
RMP

Reputation: 5381

Why doesn't RVO happen for assignment operator? (C++)

Example:

A myfunction() { return A(); }
A a = myfunction(); // default ctor only (return value optimization)
a = myfunction(); // default ctor and operator=

Why can't the compiler just write the new object into the existing object? I believe all instances of a class occupy the same amount of (non dynamic) memory, so I don't see why this would be a problem.

Upvotes: 2

Views: 1191

Answers (2)

Sebastian Redl
Sebastian Redl

Reputation: 71899

RVO happens only because the C++ standard gives compilers a special license to ignore side effects in the copy constructor and the destructor of the temporary, which won't happen once the optimization is applied.

There is no such special license to ignore side effects in the assignment operator, so that can't be omitted. Furthermore, since a is valid before it is assigned to, it would first have to be destructed so that a new object can be constructed in place. Not only is there no special license to ignore side effects introduced by this destructor call, what's worse is that the destruction would have to happen before the function call, and then where would you be if the function throws?

Upvotes: 6

Mike Seymour
Mike Seymour

Reputation: 254431

RVO works by constructing the returned value on the caller's stack frame.

In the first case, it can be constructed directly in the storage for a, since there is no object there yet.

In the second case, there is already an object there, so it will have to be constructed somewhere else before being assigned to a. You can't construct a new object on top of a, since that is not how assignment works.

Upvotes: 5

Related Questions