std::move 和 std::shared_ptr 参数按值传递

问题描述 投票:0回答:1

考虑以下代码:

#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) 中执行哪个 ctor - 复制或移动?
  2. 如果创建了(2)临时文件,则执行复制构造函数以在
    t
    中创建
    void test(std::shared_ptr<Test> t)
    ,然后销毁临时文件。这是正确的吗?
c++ move shared-ptr move-semantics
1个回答
0
投票

您的示例中总共创建了 3 个

std::shared_ptr<Test>

  1. auto t = std::make_shared<Test>(1);
  2. test(std::move(t));
    -
    t
    中的接收
    test()
    移动构造的
  3. test(std::make_shared<Test>(2));
    - 接收者
    t
    make_shared()
    创建的。由于复制/移动省略,它是同一个对象。

这里有一个 demo,它不使用

shared_ptr
,而是使用一个名为
foo
的测试类,以便您可以跟踪每个实例化。

© www.soinside.com 2019 - 2024. All rights reserved.