【发布时间】:2022-01-24 04:01:58
【问题描述】:
我想在多态情况下将派生类 unique_ptr 的所有权转移到其抽象基类 unique_ptr。怎么办?
class Fruit {
public:
virtual void print() = 0;
};
class Apple: public Fruit {
public:
string name;
virtual void print() { cout << " Apple name is " << name << endl; }
Apple(string name): name(name) {}
};
int main()
{
unique_ptr<Apple> apple = make_unique<Apple>("Rose");
unique_ptr<Fruit> fruit = dynamic_cast<unique_ptr<Fruit>>(apple); // don't work
// want to transfer ownership of apple to fruit
unique_ptr<Apple> new_apple = dynamic_cast<unique_ptr<Apple>>(fruit); // get back the ownership to the new apple
return 0;
}
【问题讨论】:
-
unique_ptr<Fruit> fruit = make_unique<Apple>("Rose");应该可以工作 -
虽然它在原始指针中很容易,但使用智能指针从派生类到基类以及反之亦然的穿梭是一个问题。
-
@JohnFilleau
Fruit需要一个虚拟析构函数来允许Apple从基类指针中销毁。 -
@Raymond 确实如此。如果想要使用多态性,应该在基类上声明一个虚拟析构函数,对吗?
-
@JohnFilleau 多态不需要虚拟析构函数。如果通过指向基类的指针删除派生类,则需要它。
标签: c++ unique-ptr