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();
have the same effect as
auto hhc = std::move(factory().get());
EDIT: I found the original proposal paper, it provides three motivating examples:
- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…