【问题标题】:Using smart pointers correctly without leaks正确使用智能指针而不会泄漏
【发布时间】:2012-09-12 09:24:06
【问题描述】:

我正在开发一个架构,我需要在不同的列表中拥有一个实体:

  • 渲染器 -> 组件列表(SpriteComponent)
  • 碰撞器 -> 组件列表(物理组件)

我认为智能指针是管理所有这些引用的最佳解决方案,所以我开始学习它,但是我遇到了一些问题,如果我正确使用它们,我很抱歉。


说明:

我有一个抽象类:IEntity

class IEntity {
  public:
    IEntity( World& world );
  private:
    World* world;
  public:
    std::tr1::weak_ptr<IEntity> weak_this;
};

typedef std::tr1::shared_ptr<IEntity> Entity;

而且我有一个在 EntityManager 中创建实体的方法:

Entity EntityManager::createEntity() {
    Entity entity( new IEntity( *this->world ) );
    entity->weak_this = entity;
    this->entityList.add( &entity );
    return entity;
}

在我的 EntityManager 类中,我有一个“实体”向量 (Of shared_ptr):

std::vector<Entity> entityList;

1 - 我是否需要在我的程序中到处使用“实体”类型(在参数中,...)?

2 - 如果我有这个:

class IComponent {
  public:
    IComponent();    
};
typedef std::tr1::shared_ptr<IComponent*> Component;

我有一个像这样的对象:

class SpriteComponent : public Component {
  public:
    SpriteComponent();        
    int texture;
};

从 shared_ptr 继承很好吗?这对我来说看起来很奇怪,但它确实有效。

3 - 我尝试使用此方法创建 10000 个实体:

Entity entity = world.getEntityManager().createEntity();

对实体的引用被推入我的“实体”向量中,如果我真的了解智能指针,则向量上的清除将删除所有实体(因为没有其他引用)。但是当我使用 cXode 泄漏分析器查看时,我可以看到没有删除实体的内存在增长。所以我刚刚尝试在我的向量中插入创建实体,但我没有泄漏,为什么?问题出在哪里 ?哦。

4 - 如果我在游戏中使用 smart_ptr,我会遇到一些性能问题吗? (我正在使用参考):

感谢您的宝贵时间!

【问题讨论】:

    标签: c++ shared-ptr smart-pointers


    【解决方案1】:
    1. 我不会称它为Entity,但可能是EntityPtr 或类似名称。 (Entity 建议它是IEntity 的具体实现)
    2. 不要从Component 派生,而是从IComponent 派生。然后,您的Component 智能指针将能够保存SpriteComponent 类型的对象。
    3. 如果不存在其他引用,EntityManager.entityList 上的清除将删除对象。但是您的代码在填充向量时似乎做了一些奇怪的事情。

      EntityPtr entity( new IEntity( *this->world ) );
      ...
      this->entityList.add( &entity );
      

      这会将实体的地址添加到实体列表中,那里不应该有&amp;。 我不确定为什么这会导致泄漏 - 但它肯定是错误的。

    4. 是的,使用智能指针会降低性能。但是,在您可以将其作为核心循环中的问题进行衡量之前,请不要担心它 - 可能永远不会有足够的惩罚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多