【发布时间】:2020-01-31 12:54:44
【问题描述】:
这些天我正在研究 C++ 左值和右值。我对下面的代码有点困惑。
class Test {
public:
Test(){}
explicit Test(int _i): i(_i) {}
void doSomething()& {
cout << "L value ref" << endl;
}
void doSomething()&& {
cout << "R value ref" << endl;
}
private:
int i;
};
void callDoSomething(Test& t) {
t.doSomething();
}
void callDoSomething(Test&& t) {
t.doSomething();
}
int main() {
auto a = Test();
callDoSomething(a);
callDoSomething(Test());
return 0;
}
在上面的代码中,我会得到这样的结果:
L value ref
L value ref
我已经通过调试器检查了上面的代码,并且很确定在这段代码中 sn-p:callDoSomething(Test()); 它将转到右值引用,即callDoSomething(Test&& t)。但是为什么还是调用左值成员函数呢?
我也试过模板,结果还是一样。
template <typename T>
void callDoSomething(T &&t) {
t.doSomething();
}
我已经阅读了this post 并且在模板版本中知道这一点。 T &&t 实际上是一个通用参考。但是在通过调试器检查之后。 t 的类型仍然是Test&&,我们可以得到Test&& &&t。通过引用折叠的定义,我们仍然应该得到Test&& t。
谁能解释为什么会这样?非常感谢!
【问题讨论】:
-
@user253751 感谢您的帖子! '它的类型是“对字符串的右值引用”,但它是该类型的左值。”'。这是有道理的。
标签: c++ c++11 rvalue-reference rvalue lvalue