【发布时间】:2020-08-30 09:12:42
【问题描述】:
我有这个逻辑:
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 也是如此。但是,在这种情况下,我认为将其保留为原始指针会更好。
【问题讨论】:
标签: c++ pointers c++17 shared-ptr