我想在多态的情况下将派生类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
管理的派生类的所有权转移到基类unique_ptr
,可以(也应该(使用移动语义。
std::unique_ptr<Derived> foo = std::make_unique<Derived>();
std::unique_ptr<Base> bar = std::move(foo);
要将所有权返回给派生的unique_ptr
,您需要弄得更混乱:
std::unique_ptr<Derived> foo = std::make_unique<Derived>();
std::unique_ptr<Base> bar = std::move(foo);
std::unique_ptr<Derived> biz(static_cast<Derived*>(bar.release()));
如果您不确定指针的实际类型,那么可以使用动态强制转换来检查它是否正确。请注意,我们在条件中使用std::unique_ptr<Base>::get()
,因为我们还不确定是否要释放所有权。如果通过,那么我们可以调用std::unique_ptr<Base>::release()
。
std::unique_ptr<Derived> foo = std::make_unique<Derived>();
std::unique_ptr<Base> bar = std::move(foo);
// dynamic cast if we're unsure that it is castable
if (dynamic_cast<Derived*>(bar.get())) {
foo.reset(static_cast<Derived*>(bar.release()));
}
看到它在行动
尝试移动分配
int main()
{
unique_ptr<Apple> apple = make_unique<Apple>("Rose");
unique_ptr<Fruit> fruit = std::move(apple);
fruit->print();
// want to transfer ownership of apple to fruit
return 0;
}