Is it a good practice to return the r-value reference from the r-value ref-qualified method?

这一生的挚爱 提交于 2019-12-11 03:02:50

问题


As I can see the general rule is not to return r-value references from functions at all (except for rare special cases). But what about class methods?

There is an example in the C++ standard library of returning r-value reference from the r-value ref-qualified method of the class (std::optional<T>::operator*() and std::optional<T>::value() methods of the std::optional<T> class). See sections 23.6.3 Class template optional [optional.optional] and 23.6.3.5 Observers [optional.observe] of the C++17 standard:

// 23.6.3.5, observers

constexpr T&& operator*() &&;
constexpr const T&& operator*() const&&;
constexpr T&& value() &&;
constexpr const T&& value() const&&;

回答1:


Consider class member access in general. Say we have a type like this:

struct A {
  int x;
};

Now let's take an object of type A.

A a;

Now the expression (a) is an lvalue, and member access (a).x is also an lvalue. But the expression std::move(a) is an rvalue, and std::move(a).x is now also an rvalue (in fact, an xvalue). This is the behaviour of member access in the core language.

Now it makes sense for user-defined types to provide user-defined behaviour that mimics the core language behaviour. We can do this by using ref-qualified member functions, which can distinguish whether the instance is an lvalue or an rvalue. When the purpose of the member function is to provide access to a subobject, then it is reasonable to return that subobject as an rvalue (specifically, an xvalue) when the instance is an rvalue.

The general advice you're presumably referring to is that you shouldn't randomly be returning rvalue references to some arbitrary objects that you don't control. In that case, it is often much better to return copies, so that your function can be used independent of contextual assumptions on lifetimes of unrelated objects. But when you're talking about member functions and the object in question is the class instance, you have a bit more control, and returning xvalues can be useful tool.

A meta lesson here is that it's not always useful to ask "whether <specific syntax X> is good practice" in C++. C++ gives you a lot of tools, and sometimes you have to talk about design in context.



来源:https://stackoverflow.com/questions/48488436/is-it-a-good-practice-to-return-the-r-value-reference-from-the-r-value-ref-quali

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