mardi 5 décembre 2017

C++ destructor call in exception outside constructor

I wasn't able to find the answer on SO or I'm not good at search what I need since I'm new to C++. I'm reading C++ primer and it suggests to use shared_ptrs but I want to try to manage memory by myself.

struct A {

 int* x;
 A(): x(new int(5)) {}
 ~A() { delete x; }
 void errorHere() {
   //code...
   throw std::runtime_error("ops");
   //code...
 }

}

Since I've a pointer I must take care of the heap. Now let's say that I run this code:

A test();
try {
 test.errorHere(); //this function throws something, for example std runtime_error
} catch (...) {
  //something
}

As you can see the errorHere(); function throws an exception and so an error comes out that interrupts the regular flow of the program. Am I sure that the destructor of the class is called when an exception happens inside his method?

In other words, when the exception occurs inside a method of the class I need to free the heap allocated memory. I am doing it in the destructor but is this called when the exception occurs?


I have seen hundreds of answers here saying that the destructor is not called if an exception occurs in the constructor but this is not my case. I'm inside a method! C++ Primer and google tell me to use smart pointers and I am ok, but I want to understand how this work so I need to know this info.

Aucun commentaire:

Enregistrer un commentaire