RVO force compilation error on failure

前端 未结 3 1589
梦毁少年i
梦毁少年i 2020-12-17 22:35

Lots of discussions here about when RVO can be done but not much about when it is actually done. As stated may times, RVO can not be guaranteed according to the Standard but

3条回答
  •  误落风尘
    2020-12-17 23:16

    Why have the compiler writers chosen to enable RVO when user defined copy constructors are in place but not when only default copy constructors are present?

    Because the standard says so:

    C++14, 12.8/31:

    When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects.

    C++14, 12.8/32

    When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. [ Note: This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided. —end note ]

    You must remember that the RVO (and other copy elisions) are optional.

    Imagine a code with deleted copy/move constructors/assignments that compiles on your compiler because the RVO kicks in. Then you move that perfectly compiling code into another compiler, where it legally fails to compile. This is not acceptable.

    This means the code must always be valid even if the compiler, for some reason, decides to NOT do the RVO optimization.

提交回复
热议问题