且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

std :: unique_ptr与派生类

更新时间:2023-11-13 14:06:52

如果它们是多态类型,并且只需要一个指向导出类型的指针,请使用 dynamic_cast

If they are polymorphic types and you only need a pointer to the derived type use dynamic_cast:

Derived *derivedPointer = dynamic_cast<Derived*>(basePointer.get());

如果它们不是多态类型,只需要一个指向导出类型的指针。 static_cast 并希望获得***效果:

If they are not polymorphic types only need a pointer to the derived type use static_cast and hope for the best:

Derived *derivedPointer = static_cast<Derived*>(basePointer.get());

如果您需要转换 unique_ptr 多态类型:

If you need to convert a unique_ptr containing a polymorphic type:

Derived *tmp = dynamic_cast<Derived*>(basePointer.get());
std::unique_ptr<Derived> derivedPointer;
if(tmp != nullptr)
{
    basePointer.release();
    derivedPointer.reset(tmp);
}

如果您需要转换 unique_ptr 包含非多态类型:

If you need to convert unique_ptr containing a non-polymorphic type:

std::unique_ptr<Derived>
    derivedPointer(static_cast<Derived*>(basePointer.release()));