简体   繁体   中英

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

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&&;

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 (in fact, an xvalue), 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM