首页 > 解决方案 > 从已存储派生类的基类的向量将 unique_ptr 实例化为派生类

问题描述

考虑以下代码:

struct  Fruit
{
   Fruit() {}
   virtual ~Fruit() {}       
   std::string name;
};

struct Banana : public Fruit
{
   std::string color;
};

struct Pineapple : public Fruit
{
   int weight;
};

这是我的 main() :

int main()
{
    std::vector<std::unique_ptr<Fruit>> product;
    product.push_back(std::unique_ptr<Banana>(new Banana)); //product[0] is a Banana
    product.emplace_back(new Pineapple);

    // I need to acess the "color" member of product[0]
    std::unique_ptr<Banana> b = std::move(product[0]); // this doesn't work, why?
    auto c = b->color;
}

product[0]我将 unique_ptr 存储到 Banana 时,为什么不能将其分配给香蕉 unique_ptr ?

标签: c++oopc++11inheritanceunique-ptr

解决方案


您需要显式转换,因为第一个产品可以是任何水果......编译器不知道这个水果是香蕉还是菠萝。

正如@IgorTandetnik 所说,你可以这样做:

std::unique_ptr<Banana> b{static_cast<Banana*>(product[0].release())};

whererelease()与 一起使用static_cast

Live demo

注意:您不能回退到使用autofor b,因为编译器会选择struct Fruit作为类型,以便为任何子类做好准备。


推荐阅读