函数的引用限定符是否有实际用例? [英] Is there any real use case for function's reference qualifiers?
本文介绍了函数的引用限定符是否有实际用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我了解了函数的引用限定符
,例如
struct foo
{
void bar() {}
void bar1() & {}
void bar2() && {}
};
在我可能需要此功能的地方,该语言功能是否有实际用例?
Where I might need this feature, is there any real use case for this language feature ?
推荐答案
基本上有两种用途:
- 为了提供优化的重载,例如将成员移出临时对象,而不必复制它。
-
防止滥用API。例如,没有人会期望
- To provide an optimized overload, for example to move a member out of a temporary object instead of having to copy it.
Prevent misuse of an API. For example, no one would expect
int a = 1 += 2;
正常工作,这也会导致编译错误。但是
to work and this would also cause a compile error. However
string b = string("foo") += "bar";
是合法的
string & operator += (string const & o);
通常是这样。同样,为您的右值提供左值引用也有令人讨厌的副作用。馊主意。可以通过将运算符声明为
as is usually the case. Also this has the nasty side-effect of providing an lvalue-reference to your rvalue. Bad idea. This can easily be prevented by declaring the operator as
string & operator += (string const & o) &;
这篇关于函数的引用限定符是否有实际用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文