Returning by Rvalue Reference: Is It More Efficient?
Returning an object by rvalue reference may not always be more efficient than returning by lvalue reference. It can lead to dangling references if the returned object is a temporary that gets destructed after the function returns.
The Original Code:
The provided code snippet attempts to return a moved rvalue reference to a temporary Beta_ab object:
Beta_ab&& Beta::toAB() const { return move(Beta_ab(1, 1)); }
This is not recommended because it returns a dangling reference. To properly move a temporary into the return value, the function should return a value rather than an rvalue reference:
Beta_ab Beta::toAB() const { return Beta_ab(1, 1); }
Using Rvalue References with Other Functions:
Returning an rvalue reference can be beneficial in certain situations. For example, if there is a getAB() function that is frequently called on temporary objects, it can be more efficient to return an rvalue reference:
struct Beta { Beta_ab ab; Beta_ab const& getAB() const& { return ab; } Beta_ab &&getAB() && { return move(ab); } };
In this example, move is necessary because ab is not a local automatic or a temporary rvalue. The ref-qualifier && ensures that the second getAB() function is invoked on rvalue temporaries, resulting in a move instead of a copy.
Conclusion:
While returning by rvalue reference can be efficient in some cases, it should be used cautiously to avoid dangling references. Returning a value is generally preferred for functions that return temporary objects.
The above is the detailed content of Is Returning by Rvalue Reference Always More Efficient Than Returning by Lvalue Reference?. For more information, please follow other related articles on the PHP Chinese website!