从存储了派生 class 的基础 class 的向量实例化 unique_ptr 到派生 class
Instantiate unique_ptr to derived class from vector of base class where derived class has been stored
考虑以下代码:
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?
您需要显式转换,因为第一个产品可以是任何水果...编译器不知道这个水果是香蕉还是菠萝。
正如@IgorTandetnik 所说,您可以这样做:
std::unique_ptr<Banana> b{static_cast<Banana*>(product[0].release())};
其中 release()
is used, along with static_cast
.
注意:您不能回退到对 b 使用 auto
,因为编译器会选择 struct Fruit
作为类型,以便为任何子类做准备。
您不想转移所有权,所以只转换指针:
auto& banana = dynamic_cast<Banana&>(*product[0]);
auto c = b->color;
如果您确定 Fruit
确实是 Banana
,dynamic_cast
可能会被 static_cast
替换。
如果您错了,static_cast
会导致 UB,而您可以使用 dynamic_cast
检查有效性(强制转换为引用或空指针强制转换为指针除外)。
考虑以下代码:
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?
您需要显式转换,因为第一个产品可以是任何水果...编译器不知道这个水果是香蕉还是菠萝。
正如@IgorTandetnik 所说,您可以这样做:
std::unique_ptr<Banana> b{static_cast<Banana*>(product[0].release())};
其中 release()
is used, along with static_cast
.
注意:您不能回退到对 b 使用 auto
,因为编译器会选择 struct Fruit
作为类型,以便为任何子类做准备。
您不想转移所有权,所以只转换指针:
auto& banana = dynamic_cast<Banana&>(*product[0]);
auto c = b->color;
如果您确定 Fruit
确实是 Banana
,dynamic_cast
可能会被 static_cast
替换。
如果您错了,static_cast
会导致 UB,而您可以使用 dynamic_cast
检查有效性(强制转换为引用或空指针强制转换为指针除外)。