为成员函数允许l值和r值引用限定符的目的是什么?

时间:2020-11-27 18:48:23

I am primarily trying to understand the uses that this feature enables or facilitates. I understand which calls go where in the following:

我主要是试图理解这个特性支持或促进的用途。我知道哪一个电话是去哪里的:

struct Foo
{
   void bar() & {std::cout << "l-value"; }
   void bar() && {std::cout << "r-value"; }
};

Foo f;
f.bar();     // calls l-value version
Foo().bar(); // call r-value version

But what is the practical use of such a distinction?

但这种区别的实际用途是什么呢?

1 个解决方案

#1


2  

An rvalue method may safely move from or otherwise invalidate the invocant, because it won't be accessible afterwards (it must not return or store the reference, of course). So in cases where a destructive implementation of some operation is more efficient, you can provide it for rvalues only where it is safe to use. Moving from also comes into consideration for cast operators.

一个rvalue方法可以安全地从或其他无效的调用中移动,因为它以后不能访问(当然,它不能返回或存储引用)。因此,如果某些操作的破坏性实现更有效,那么您可以仅在安全使用的地方提供rvalues。从另一个角度来看,也考虑到铸造操作符。

#1


2  

An rvalue method may safely move from or otherwise invalidate the invocant, because it won't be accessible afterwards (it must not return or store the reference, of course). So in cases where a destructive implementation of some operation is more efficient, you can provide it for rvalues only where it is safe to use. Moving from also comes into consideration for cast operators.

一个rvalue方法可以安全地从或其他无效的调用中移动,因为它以后不能访问(当然,它不能返回或存储引用)。因此,如果某些操作的破坏性实现更有效,那么您可以仅在安全使用的地方提供rvalues。从另一个角度来看,也考虑到铸造操作符。