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

爷,独闯天下 提交于 2019-12-23 02:44:12

问题


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.


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/20250043/why-doesnt-rvo-happen-for-assignment-operator-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!