search

Home  >  Q&A  >  body text

c++ - unique_ptr如何向下转换?

class A
{
public:
    void test() { std::cout << "test" << std::endl; }
};

class B : public A
{
public:
    void test2() { std::cout << "test2" << std::endl; }
};

std::unique_ptr<A> Get()
{
    std::unique_ptr<A> b(new B);
    return b;
}

int main()
{
    auto o = Get();  // 如何转换为 std::unique_ptr<B> ?
    system("pause");
    return 0;
}
巴扎黑巴扎黑2803 days ago608

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:13:19

    Direct conversion (downcasting/dynamic_cast) will cause errors.

    You should first take out the pointer of dynamic type in unique_ptr b:

    B* ptr = dynamic_cast<B*>(o.get());
    

    Then redefine a new unique_ptr, then release the original pointer and reset the new pointer:

    std::unique_ptr<B> anotherptr;
    if (ptr != nullptr) {
        o.release();
        anotherptr.reset(ptr);
    }
    

    reply
    0
  • 阿神

    阿神2017-04-17 13:13:19

    unique_ptr<A> 与 unique_ptr<B> 之间无法直接转换,必须把原指针取出来再进行转换
    int main()
    {
        auto o = Get();  
        std::cout << typeid(o).name() << std::endl;
        auto x = reinterpret_cast<B*>(o.release());
        std::unique_ptr<B> b(x);
        std::cout << typeid(b).name() << std::endl;
        system("pause");
        return 0;
    }

    stdout:

    class std::unique_ptr<class A,struct std::default_delete<class A> >
    class std::unique_ptr<class B,struct std::default_delete<class B> >

    reply
    0
  • Cancelreply