[英]Why is move-constructor not called?
我有以下代码:
#include <iostream>
using namespace std;
struct T {
int a;
T() = default;
T(T& other)
{
cout << "copy &\n";
}
T(T&& other)
{
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;
}
我不明白,为什么复制构造函数优于移动构造函数,即使foo()
接受右值引用。
x
本身就是一个左值,即使它的类型是右值引用。 您需要使用std::move
将其转换为右值,就像在main()
中的x
上使用std::move
一样。
void foo(T&& x)
{
T y(std::move(x));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.