【发布时间】:2019-05-13 16:16:03
【问题描述】:
考虑以下代码:
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 ?
【问题讨论】:
-
编译器不知道
product[0]指向Banana而不是其他Fruit。如果您确定这一点,您可以通过强制转换告诉编译器。例如std::unique_ptr<Banana> b{static_cast<Banana*>(product[0].release())}; -
使用 release() 我的产品[0] 丢失了。我不希望这种情况发生,因为我打算再次使用它。还有其他方法吗?
-
如果要编译它,
std::unique_ptr<Banana> b = std::move(product[0]);也会同样丢失,所以我认为这就是你想要的。如果您不是要从向量中获取所有权,请将其设为auto b = static_cast<Banana*>(product[0].get());
标签: c++ oop c++11 inheritance unique-ptr