考虑以下代码:
#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)
}
问题:
t
中创建void test(std::shared_ptr<Test> t)
,然后销毁临时文件。这是正确的吗?您的示例中总共创建了 3 个
std::shared_ptr<Test>
:
auto t = std::make_shared<Test>(1);
test(std::move(t));
- t
中的接收test()
是移动构造的。test(std::make_shared<Test>(2));
- 接收者t
是由make_shared()
创建的。由于复制/移动省略,它是同一个对象。这里有一个 demo,它不使用
shared_ptr
,而是使用一个名为 foo
的测试类,以便您可以跟踪每个实例化。