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

C++含std::string成员的类移动构造调用string拷贝构造,实现是否有误?

问题原因

你的移动构造函数实现存在错误,核心问题是参数错误添加了const修饰符。

原理说明

  • 你声明的移动构造是Test( const Test &&that ),这意味着参数that的所有成员都带const属性
  • 你对that.s调用std::move时,返回值类型是const std::string&&,属于带const的右值引用
  • 标准库std::string的移动构造函数签名为basic_string( basic_string&& ),仅接受非const的右值引用,const std::string&&无法匹配这个重载
  • 重载决议会降级匹配接受const std::string&参数的拷贝构造函数,也就是你反汇编看到的结果

修复方案

移动构造的本质是转移源对象的资源,必然会修改源对象的状态,因此参数不应该加const修饰,修改移动构造声明即可:

Test(Test &&that) : i(that.i), s(std::move(that.s)) {
    cout << "move constructor." << endl;
}

修改后重新编译,反汇编就能看到std::string的移动构造被正确调用。

内容的提问来源于stack exchange,提问作者pasaba por aqui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:42:03