mou*_*_00 4 c++ rvalue lvalue rvalue-reference c++11
我有以下代码:
#include <iostream>
struct T {
int a;
T() = default;
T(T& other) {
std::cout << "copy &\n";
}
T(T&& other) {
std::cout << "move &&\n";
}
};
void foo(T&& x) {
T y(x); // why is copy ctor called??????
}
int main() {
T x;
foo(std::move(x));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
foo()我不明白为什么即使接受右值引用,复制构造函数也优于移动构造函数。
x本身就是一个左值,即使它的类型是右值引用。值类别和类型是两个独立的属性。
即使变量的类型是右值引用,由其名称组成的表达式也是左值表达式;
您需要使用 usestd::move将其转换为右值,就像在 中使用std::moveon一样。xmain()
void foo(T&& x)
{
T y(std::move(x));
}
Run Code Online (Sandbox Code Playgroud)