You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何移动构造函数未执行?VS2019下C++代码疑问

为什么Test对象c调用拷贝构造而非移动构造?

以下是运行在VS2019、Release、x86环境下的代码:

#include<iostream>
class Test
{
public:
    int num{ 0 };
    Test(int num1) : num(num1) {}
    Test(const Test& rhs)
    {
        std::cout << "copy\n";
        num = rhs.num;
    }
    Test(Test&& rhs)
    {
        std::cout << "move\n";
        num = std::move(rhs.num);
    }
};

int main()
{
    Test a(10);
    Test&& b = std::move(a);
    Test c(b);    // 此处调用拷贝构造
    Test d(std::move(a));  // 此处调用移动构造
    Test e(static_cast<Test&&>(a));   // 此处调用移动构造
}

程序输出:

copy
move
move

核心原因

右值引用变量本身是左值。

你定义的Test&& b = std::move(a);中,b是一个有名字的右值引用变量。编译器判定左值的关键依据是「是否有名字、能否被取地址」——b满足这两个条件,因此会被当作左值处理。

当用b初始化c时,编译器会匹配接受左值引用的拷贝构造函数(const Test&),因此执行拷贝构造,输出copy。

而std::move(a)和static_cast<Test&&>(a)的作用是将a强制转换为无名字的右值引用(将亡值),这类值不满足左值的判定条件,因此会匹配接受右值引用的移动构造函数,执行移动操作,输出move。

内容的提问来源于stack exchange,提问作者Xia Qizhen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 17:14:57