代码之家  ›  专栏  ›  技术社区  ›  jjmcc

是否可以将常量唯一\u ptr引用(派生类)转换为共享\u ptr(基类)

  •  2
  • jjmcc  · 技术社区  · 7 年前
    std::vector<std::unique_ptr<Projectile>> const& projectiles = m_projectileManager->GetProjectiles();
    std::vector<std::vector<std::unique_ptr<Enemy>>> const& enemies = m_enemyManager->GetEnemies();
    
    std::vector<std::unique_ptr<EntityBoundingBox>> boundingBoxes;
    for (std::unique_ptr<Projectile>const& projectile : projectiles) {
        std::shared_ptr<Entity> entity = std::move(projectile); //error
    
        std::unique_ptr<EntityBoundingBox> boundingBox = std::make_unique<EntityBoundingBox>(projectile->GetBoundingBox(), entity);
        boundingBoxes.push_back(std::move(boundingBox));
    }
    

    我正在尝试创建一个新对象, EntityBoundingBox 但是我需要保留一个原始的参考 Entity 为了确定什么与什么发生了冲突,但由于我对实体使用unique_ptr,我似乎无法将它们传递给新类。我还试图存储类型 实体 哪一个是 Projectile

    有没有一种方法可以做到这一点,而不必将存储数据的唯一\u ptr更改为共享\u ptr 投射物 和 Enemy

    建造师

    EntityBoundingBox(std::shared_ptr<BoundingBox> boundingBox, std::shared_ptr<Entity> entity)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   David Schwartz    7 年前

    unique_ptr<>const& ,您无权延长被引用对象的寿命。当潜在的 unique_ptr 你有一个参考去了,对象也去了。但是如果你有 shared_ptr<>

    想想你为什么会通过考试,也许会有所帮助 shared_ptr 到某段代码。除非该代码可能需要延长被引用对象的生命周期,否则传递引用就更有意义。如果你路过一个 共享ptr ,这是因为该代码可能会复制它 并期望它能延长物体的寿命。如果其他东西会破坏该对象,那么这就不起作用了。