C ++ shared_ptr操作逻辑

时间:2020-08-30 09:12:42

标签: c++ pointers c++17 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也是如此。但是,在这种情况下,我认为将其保留为原始指针会更好。

1 个答案:

答案 0 :(得分:1)

如果您不想在接口中公开所有权(更不用说转移所有权了),则很明显地返回 raw 指针(或某些特殊的观察者指针类型,如果使用的话)正确的想法。 (尤其是避免使用const std::shared_ptr<T>& foo()之类的结构,这些结构对于某些所有权 elsewhere 毫无意义。)这种方法还可以节省一些引用计数的麻烦,并且与您的显式专业兼容。 / p>

相关问题