如何解决C ++ shared_ptr操作逻辑
我有这个逻辑:
struct Foo;
struct Bar;
struct IComponent {
virtual Foo * GetFoo() { return nullptr; }
virtual Bar * GetBar() { return nullptr; }
}
struct Foo : public IComponent {
Foo * GetFoo() override { return this; }
}
struct Bar : public IComponent {
Bar * GetBar() override { return this; }
}
组件由
管理class SimpleObject {
public:
void Add(IComponent * b){
components.push_back(b);
if (b->GetFoo()) foo = b->GetFoo();
}
template <typename T>
T * GetComponent() const {
for (size_t i = 0; i < components.size(); i++){
if (T * tmp = dynamic_cast<T *>(components[i])){
return tmp;
}
}
return nullptr;
}
private:
Foo * foo;
std::vector<IComponent *> components;
}
template <> Foo * SimpleObject::GetComponent<Foo>() const {
return this->foo;
}
我可以有多个不同的SimpleObject
。但是,它们每个可以包含相同或不同的组件(一个组件可以分配给多个SimpleObject
)。 GetComponent
仅用于访问关联的组件。不应有所有权转移(但是,我不知道如何强制这样做,因为库用户当然可以错误地或我的错误来做到这一点)-组件彼此之间不认识,只能通过它们SimpleObject
关联。
现在,我不喜欢原始指针。我将std::vector<IComponent*>
转换为std::vector<std::shared_ptr<IComponent>>
,并将void Add(IComponent* b)
转换为void Add(std::shared_ptr<IComponent> b)
。
但是,我不确定如何管理GetComponent
方法。我是否还应该将其返回类型转换为shared_ptr
还是更好地坚持使用原始指针并通过.get()
返回?辅助变量foo
也是如此。但是,在这种情况下,我认为将其保留为原始指针会更好。
解决方法
如果您不想在接口中公开所有权(更不用说转移所有权了),则很明显地返回 raw 指针(或某些特殊的观察者指针类型,如果使用的话)正确的想法。 (尤其是避免使用const std::shared_ptr<T>& foo()
之类的结构,这些结构对于某些所有权 elsewhere 毫无意义。)这种方法还可以节省一些引用计数的麻烦,并且与您的显式专业兼容。 / p>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。