我刚刚发现这是有效的C++:
struct S {
int f() &; // !
int g() const &; // !!
};
int main() {
S s;
s.f();
s.g();
}this通过引用传递给f,通过const-reference传递到g .
这对任何人都有用吗?
发布于 2022-04-12 17:15:16
它们对于提供安全和优化都很有用。
对于返回指向它们所拥有的东西的指针的成员函数(直接或通过视图类型(如std::string_view或std::span) ),禁用rvalue重载可以防止错误:
struct foo {
int* take_ptr_bad() { return &x; }
int* take_ptr() & { return &x; }
int x;
};
foo get_foo();
void bar() {
auto ptr = get_foo().take_ptr_bad();
// ptr is dangling
auto ptr = get_foo().take_ptr();
// does not compile
}另一种是提供一些优化。例如,如果this是一个rvalue以防止不必要的副本,您可能会重载一个getter函数返回一个rvalue引用:
struct foo {
const std::string& get_str() const & {
return s;
}
std::string&& get_str() && {
return std::move(s);
}
std::string s;
};
void sink(std::string);
foo get_foo();
void bar() {
sink(get_foo().get_str());
// moves the string only if the r-value overload is provided.
// otherwise a copy has to be made, even though the foo object
// and transitively the string is temporary.
}这就是我使用这个特性的方式,我相信还有更多的用例。
https://stackoverflow.com/questions/71844996
复制相似问题