首页 > 解决方案 > 将 shared_ptr 传递给函数 - 需要澄清

问题描述

我和会员有一堂课

vector<shared_ptr<ParticleSystem>> particleSystems;

有一个方法

void AddParticleSystem(shared_ptr<ParticleSystem> const sys)
{
    particleSystems.push_back(sys);
}

注意参数。该方法是这样调用的:

shared_ptr<ParticleSystem> psys = make_shared<ParticleSystem>(...);
scene.AddParticleSystem(psys);

它有效,但为什么呢?这不是共享的吗?


默认情况下,我不会尝试传递指针。在考虑函数参数时,我要么const&在不希望更改传递变量的任何内容时使用,要么&在计划使用将更改给定变量成员的方法时使用。

所以默认情况下,我实现了上述方法,如下所示:

void AddParticleSystem(ParticleSystem const& sys)
{
    particleSystems.push_back(std::make_shared<ParticleSystem>(sys));
}

我称之为

shared_ptr<ParticleSystem> psys = make_shared<ParticleSystem>(...);
scene.AddParticleSystem(*psys);

这次它没有编译,说明

错误 C2280 'Physics::ParticleSystem::ParticleSystem(const Physics::ParticleSystem &)':试图引用已删除的函数

我使用(我使用VS)追溯了这个问题Output,这导致我

particleSystems.push_back(std::make_shared<ParticleSystem>(sys));

make_shared准确地说,是方法。

现在,这ParticleSystem扩展Visual了具有构造函数和成员的

Visual(string const &name, string const &path, const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr, bool gamma = false)
{
    this->name = string().append(name);
    model = make_unique<Model>(path, gamma);
    material = make_unique<Material>();
    shader = make_unique<Shader>(vertexPath, fragmentPath, geometryPath);
}

unique_ptr<Shader> shader;
unique_ptr<Material> material;
unique_ptr<Model> model;
virtual ~Visual() = default;

make_shared需要以某种方式复制东西。问题是 a ParticleSystemwhich is aVisualunique_ptr成员并且默认make_shared不知道如何对待他们?

这是编译器删除我的默认复制构造函数的原因吗?如果是这样,如果我为所有拥有的类Visual(包括它自己)实现一个复制构造函数,我可以将它ParticleSystem const&作为参数传递吗?

标签: c++

解决方案


a 的每个副本shared_ptr都是一个句柄,通过它可以访问共享对象。您可以传递shared_ptr对它或它的副本的引用,并将它的副本存储在集合中。s 的副本shared_ptr引用相同的底层对象。当shared_ptr指向同一个底层对象的最后一个被销毁时,底层对象也被销毁。


推荐阅读