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

std::move与按值传递std::shared_ptr参数的技术问题

问题解答

代码示例

#include <iostream>
#include <memory>

class Test
{
    public:
    Test(int t) : t(t) {}
    
    int t;
};

void test(std::shared_ptr<Test> t)
{
    std::cout << t.use_count() << std::endl;
}

int main()
{
    auto t = std::make_shared<Test>(1);
    test(std::move(t)); //(1)
    test(std::make_shared<Test>(2)); //(2)
}

问题1解答

在标记(1)的调用场景中,执行的是移动构造函数。

std::move(t)把原本的左值std::shared_ptr<Test>对象转换成了右值引用,当test函数以值传递方式接收这个右值时,会触发std::shared_ptr的移动构造逻辑——移动构造不会增加引用计数,只是直接转移对象的所有权,所以此时test函数内输出的t.use_count()是1,原变量t在移动后会变成空的shared_ptr。

问题2解答

该描述不正确,核心原因有两点:

  1. 复制消除(RVO)优化:C++标准允许编译器直接在test函数形参的内存位置构造std::make_shared<Test>(2)的返回对象,完全跳过“创建临时对象再拷贝”的步骤,这是主流编译器默认开启的标准优化行为。
  2. 即便不考虑优化,std::make_shared返回的是临时右值,std::shared_ptr接收右值时会调用移动构造函数而非拷贝构造函数,不会触发引用计数的增长,根本不存在“拷贝构造生成形参”的过程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:12:34