c++ - 将 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 ParticleSystem
which is aVisual
有unique_ptr
成员并且默认make_shared
不知道如何对待他们?
这是编译器删除我的默认复制构造函数的原因吗?如果是这样,如果我为所有拥有的类Visual
(包括它自己)实现一个复制构造函数,我可以将它ParticleSystem const&
作为参数传递吗?
解决方案
a 的每个副本shared_ptr
都是一个句柄,通过它可以访问共享对象。您可以传递shared_ptr
对它或它的副本的引用,并将它的副本存储在集合中。s 的副本shared_ptr
引用相同的底层对象。当shared_ptr
指向同一个底层对象的最后一个被销毁时,底层对象也被销毁。
推荐阅读
- android - Firestore 安全规则未按预期工作
- multithreading - 无法跨具有 mpsc::Sender 作为字段的线程发送结构
- python - 在 AMBER 套件环境中运行 Python 脚本的问题
- python - 如何使用 python pandas 为 url、api 和日期约束编写一个 for 循环
- java - TypeMappingException:检测到具有不同返回类型的操作“opName”的多个方法
- docker - 将 CI 容器中的卷挂载到 docker-compose 容器中
- android - 在 rxjava 中订阅消费者?
- api-design - 如何在 Qlik Sense 中创建一个触发成功任务的任务
- android - 找不到 com.android.tools.build:gradle:3.6.2
- excel - 根据标题和前列设置单元格范围值