在引用限定符上重载成员函数的用例是什么? [英] What's a use case for overloading member functions on reference qualifiers?
问题描述
C ++ 11可以根据参考限定词重载成员函数:
C++11 makes it possible to overload member functions based on reference qualifiers:
class Foo {
public:
void f() &; // for when *this is an lvalue
void f() &&; // for when *this is an rvalue
};
Foo obj;
obj.f(); // calls lvalue overload
std::move(obj).f(); // calls rvalue overload
我理解这是如何工作的,但是它的用例是什么?
I understand how this works, but what is a use case for it?
我看到 N2819 建议将标准库中的大多数赋值运算符限制为左值目标(即向赋值运算符添加&
引用限定符),但这已被拒绝。这是一个潜在的用例,委员会决定不去使用它。
I see that N2819 proposed limiting most assignment operators in the standard library to lvalue targets (i.e., adding "&
" reference qualifiers to assignment operators), but this was rejected. So that was a potential use case where the committee decided not to go with it. So, again, what is a reasonable use case?
推荐答案
在提供引用getter的类中,ref-qualifier重载可以当从右值提取时激活移动语义。例如:
In a class that provides reference-getters, ref-qualifier overloading can activate move semantics when extracting from an rvalue. E.g.:
class some_class {
huge_heavy_class hhc;
public:
huge_heavy_class& get() & {
return hhc;
}
huge_heavy_class const& get() const& {
return hhc;
}
huge_heavy_class&& get() && {
return std::move(hhc);
}
};
some_class factory();
auto hhc = factory().get();
这似乎很大的努力投资只有更短的语法
This does seem like a lot of effort to invest only to have the shorter syntax
auto hhc = factory().get();
的效果与
auto hhc = std::move(factory().get());
编辑:我发现原始提案文件,它提供了三个激励示例:
I found the original proposal paper, it provides three motivating examples:
- 限制
operator =
到lvalues(TemplateRex的回答) - 启用成员移动
- 约束
运算符&
到左值。我想这是明智的,以确保指针最终解除引用时,pointee更有可能活着:
- Constraining
operator =
to lvalues (TemplateRex's answer) - Enabling move for members (basically this answer)
- Constraining
operator &
to lvalues. I suppose this is sensible to ensure that the "pointee" is more likely to be alive when the "pointer" is eventually dereferenced:
struct S {
T operator &() &;
};
int main() {
S foo;
auto p1 = &foo; // Ok
auto p2 = &S(); // Error
}
不能说我曾亲自使用过运算符&
超载。
Can't say I've ever personally used an operator&
overload.
这篇关于在引用限定符上重载成员函数的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!