0

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).

Claudio
  • 10,614
  • 4
  • 31
  • 71
samnaction
  • 1,194
  • 1
  • 17
  • 45

3 Answers3

3

It won't. You're not using RAII. Use a smart pointer.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

The point of RAII is to use variables with automatic storage duration to achieve exception-safety. You could use a smart pointer if you need an object of dynamic storage duration, or you could simply create an object with automatic storage duration to begin with:

try
{
    B bobj;
    A *b = &bobj;

    b->mymethod();

}

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

When the stack is unwound because of an exception, all variables with automatic storage duration are properly destroyed, so the smart pointer can deallocate the object in its destructor, and in this example here the object bobj would also be destroyed as it should.

alain
  • 11,939
  • 2
  • 31
  • 51
0

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
Community
  • 1
  • 1
sp2danny
  • 7,488
  • 3
  • 31
  • 53