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).
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:
unique_ptr
. This wont be copyable.shared_ptr
. This will do shallow copy.clone_ptr
. This will do deep copy.