std::unique_ptr with derived class

前端 未结 1 773
栀梦
栀梦 2020-12-05 07:13

I have a question about the c++11 pointers. Specifically, how do you turn a unique pointer for the base class into the derived class?

class Base
{
public:
           


        
相关标签:
1条回答
  • 2020-12-05 08:12

    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());
    

    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());
    

    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);
    }
    

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

    std::unique_ptr<Derived>
        derivedPointer(static_cast<Derived*>(basePointer.release()));
    
    0 讨论(0)
提交回复
热议问题