Returning std::vector by value

前端 未结 2 1942
庸人自扰
庸人自扰 2020-12-14 18:47

It is often said that in C++11 it is sane to return std::vector by value.

In C++03 this was mostly true as RVO should optimize away the copy. But that

2条回答
  •  失恋的感觉
    2020-12-14 19:26

    In C++11 will a returned std::vector local variable always be moved?

    For a local variable, even a by-value parameter, the compiler has to always attempt to move it first (if neither the move nor the copy can be elided for whatever reason, even if the criteria are met). If that fails, it tries again with a copy:

    §12.8 [class.copy] p32

    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 ]

    What if that vector is a member of a local variable instead of a local variable itself?

    A subobject will not be tried to be moved, as that doesn't meet the criteria for copy elision. (Which is dumb, IMHO, but that's how it currently is. I don't think the two should be linked, since a subobject can perfectly fine be moved if it's local.)

    Obviously returning a global variable will not be moved. What other cases will it not be moved?

    A reference will obviously not be moved. Other than that, I can't really think of anything else.

提交回复
热议问题