Search code examples
c++raii

C++ RAII and polymorphism compatibility


There is no finally block in C++ because of RAII. Now if I have a pointer object and exception happens in one of the method, how this object will be deleted?. Here is a sample code I have written.

class A
{
public:
    A()
    {
        cout<<"I am inside A\n";
    }

    virtual void mymethod()
    {
        throw 0;
    }

    virtual ~A()
    {
        cout<<"A destroyed\n";
    }
};

class B : public A
{
public :
    //A a;

    B()
    {
        cout<<"I am inside B \n";
    }

    virtual void mymethod()
    {
        throw 0;
    }

    ~B()
    {
        cout<<"B destroyed\n";
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        A *b = new B();

        b->mymethod();

        delete b;
    }

    catch (int i)
    {
        cout<<"exception";
    }
    return 0;
}

Now in this how to delete the pointer object (b).


Solution

  • First of, all polymorphic types should have virtual destructors.
    Second, when you use owning raw pointers, you basically disable RAII.
    The solution is to use a smart-pointer:

    • If you want a unique asset, use unique_ptr. This wont be copyable.
    • If you want a shared asset, use shared_ptr. This will do shallow copy.
    • If you want value-semantics, use clone_ptr. This will do deep copy.
      It's from the next standard, but you can find it here