繁体   English   中英

为什么不调用移动构造函数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM