c++ - unique_ptr如何向下转换?
巴扎黑
巴扎黑 2017-04-17 13:11:19
0
2
613
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;
}
巴扎黑
巴扎黑

reply all(2)
小葫芦

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);
}
阿神
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> >
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template