我和会员一起上课
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&
when 希望不更改传递的变量上的任何内容,要么使用&
when 计划使用将更改给定变量成员的方法。
所以默认情况下,我像这样实现了上述方法:
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 &)':试图引用已删除的函数
我使用Output
(我使用 VS)追溯了这个问题,这导致我
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
需要以某种方式复制东西。问题ParticleSystem
是 aVisual
有unique_ptr
成员并且默认情况下make_shared
不知道如何对待它们?
这是编译器删除我的默认复制构造函数的原因吗?如果是这样,如果我为所有具有的类Visual
(包括它自己)实现一个复制构造函数,我可以将它ParticleSystem const&
作为参数传递吗?
a 的每个副本shared_ptr
都是一个句柄,通过它可以访问共享对象。您可以传递shared_ptr
对它或它的副本的引用,并将它的副本存储在集合中。shared_ptr
s 的副本引用相同的底层对象。当最后shared_ptr
一个引用相同底层对象的对象被销毁时,底层对象也被销毁。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句