在 C++ 中,不可能将 r 值参数绑定到非const
l 值引用。但我注意到,当我调用 r-value 对象时,返回*this
它的方法会以某种方式编译。
示例:不经意间,这段代码将无法编译
class X
{
};
void bar(X&)
{
}
int main()
{
foo(X{}); // invalid initialization of non-const reference of type 'X&' from an rvalue of type 'X'
}
但是添加一个简单的方法X
使其可编译:
class X
{
public:
X& foo() { return *this; }
};
void bar(X&)
{
}
int main()
{
bar(X{}.foo());
}
为什么它有效?是不是说调用后右foo
值对象就变成左值对象了?使用这种结构是否安全?有没有其他方法可以在不创建新方法(类似X.this
)的情况下达到类似的效果?