我想在多态情况下将派生类 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()));
}
关于c++ - 将派生类 unique_ptr 的所有权转移到其抽象基类 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70457355/