简体   繁体   English

使用unique_ptr的C ++ static_cast和dynamic_cast多态类

[英]C++ static_cast and dynamic_cast of polymorphic classes using unique_ptr

I was practicing static_cast and dynamic_cast on polymorphic classes in C++. 我在C ++中的多态类上练习static_cast和dynamic_cast。 I tried it using both raw pointers and unique_ptr. 我尝试使用原始指针和unique_ptr。 While the former doesn't create problems, the later does. 前者不会造成问题,而后者会造成问题。 Here I present my code:- 在这里,我介绍我的代码:-

#include <iostream>
#include <memory>
#include <exception>
#include <stdexcept>
using namespace std;

class A
{
    int a, id=0;
    static int i;
public:
    A()
    {
        id=++i;
        cout<<"constructing A: "<<id<<"\n";
    }
    virtual void get()
    {
        cout<<"enter a: ";
        cin>>a;
    }
    virtual void disp()
    {
        cout<<"a = "<<a<<"\n";
    }
    virtual ~A()
    {
        cout<<"destroying A: "<<id<<"\n";
    }
};
int A::i=0;
class B: public A
{
    int b;
public:
    B()
    {
        cout<<"constructing B\n";
    }
    void get()
    {
        cout<<"enter b: ";
        cin>>b;
    }
    void disp()
    {
        cout<<"b = "<<b<<"\n";
    }
    ~B()
    {
        cout<<"destroying B\n";
    }
};

void show (unique_ptr<B> &p)
{
    p->get();
    p->disp();
}
void d_cast (unique_ptr<A> &pa)
{
    unique_ptr<B> pb;
    try
    {
        pb.reset(dynamic_cast<B*>(pa.release()));
        if (pb==nullptr)
            throw runtime_error {"nullptr exception"};
        show(pb);
        cout<<"dynamic_cast successful\n\n";
    }
    catch (exception &e)
    {
        cout<<"dynamic_cast unsuccessful: "<<e.what()<<"\n\n";
    }
    pa.reset(pb.release());
}
void s_cast (unique_ptr<A> &pa)
{
    unique_ptr<B> pb;
    try
    {
        pb.reset(static_cast<B*>(pa.release()));
        if (pb==nullptr)
            throw runtime_error {"nullptr exception"};
        show(pb);
        cout<<"static_cast successful\n\n";
    }
    catch (exception &e)
    {
        cout<<"static_cast unsuccessful: "<<e.what()<<"\n\n";
    }
    pa.reset(pb.release());
}

int main()
{
    cout<<R"(using "unique_ptr<A> pa with new A" :-)"<<"\n\n";
    unique_ptr<A> pa(new A);    // (1)
    d_cast(pa);
    s_cast(pa);      // (2)
    cout<<"\n"<<R"(using "unique_ptr<A> pa with new B" :-)"<<"\n\n";
    pa.reset(new B);
    d_cast(pa);
    s_cast(pa);
    return 0;
}

The output of the code is:- 代码的输出是:-

using "unique_ptr<A> pa with new A" :-

constructing A: 1
dynamic_cast unsuccessful: nullptr exception

static_cast unsuccessful: nullptr exception


using "unique_ptr<A> pa with new B" :-

constructing A: 2
constructing B
enter b: 7
b = 7
dynamic_cast successful

enter b: 8
b = 8
static_cast successful

destroying B
destroying A: 2

I have only 2 questions as I have marked already:- 我已经标记了两个问题:-

  1. Why isn't the first object {denoted by (1)} destroyed whereas the one called with "new B" is destroyed ? 为什么第一个对象(由(1)表示)没有被销毁,而被“新B”调用的对象却被销毁了呢?

  2. Why is (2) throwing the exception ? 为什么(2)抛出异常? Interestingly if i reverse the positioning of s_cast(pa) and d_cast(pa) then (2) doesn't throw any exception and works fine (problem (1) still persists however). 有趣的是,如果我反转s_cast(pa)d_cast(pa)的位置,则(2)不会抛出任何异常并且工作正常(问题(1)仍然存在)。

Ok ! 好 ! So you need to change your function d_cast function definition like this:- 因此,您需要像下面这样更改函数d_cast函数定义:-

void d_cast (unique_ptr<A> &pa)
{
unique_ptr<B> pb;
A *aptr=pa.release();   // make a pointer of type A
try
{
    pb.reset(dynamic_cast<B*>(aptr));   // assign aptr instead of pa.release() here
    if (pb==nullptr)
    throw runtime_error {"nullptr exception"};
    show(pb);
    cout<<"dynamic_cast successful\n\n";
    pa.reset(pb.release());   // reset pa with pb.release() and not with aptr becomes pb has the ownership of aptr
}
catch (exception &e)
{
    cout<<"dynamic_cast unsuccessful: "<<e.what()<<"\n\n";
    pa.reset(aptr);    // reset aptr back to pa as pb holds no ownership of aptr
}
}

As you must be knowing the d_cast would fail and thus the expression of dynamic_cast<B*>(pointer_of_type_A) would return nullptr . 您必须知道d_cast将会失败,因此dynamic_cast<B*>(pointer_of_type_A)的表达式将返回nullptr If there would have been a reference instead of pointer then std::bad_cast exception would be thrown. 如果存在引用而不是指针,则将引发std::bad_cast异常。 But because you are using the release() function, the unique_ptr object pa gets rid of the ownership of the pointer and there is no object or pointer to trace it back. 但是由于使用的是release()函数,unique_ptr对象pa摆脱了指针的所有权,并且没有对象或指针可以对其进行追溯。 Thus you should use A *aptr to hold the released pointer and return it to pa if the casting fails. 因此,您应该使用A *aptr来保存释放的指针,如果转换失败,则将其返回到pa

If you do so, your both problems are solved 如果这样做,两个问题都可以解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM