3
votes

Can somebody explain here how destructor is called for object created in heap via new operator when the corresponding delete is not called. In addition since in below code we are catching object via const reference and in destructor we are changing object value (i.e. setting n=0), so how is that possible.

class A
{
    private:
        int n;
    public:
        A()
        {
            n=100;
            std::cout<<"In constructor..."<<std::endl;
        }
        ~A()
        {
            n=0;
            std::cout<<"In destructor..."<<std::endl;
        }
};
int main()
{
  try
  {
      throw *(new A());
  }
  catch(const A& obj)
  {
      std::cout<<"Caught...."<<std::endl;
  }

 return 0;
}

Output from program (running on http://cpp.sh/3jm4x):

In constructor...
Caught....
In destructor...
2
And you know that the destructor is called because...? Have you tried running in a debugger, setting a breakpoint in the destructor to see where it's called from? - Some programmer dude
apologies here is the link : cpp.sh/3jm4x - PapaDiHatti
Even though it might be elided, I suggest you add a copy-constructor as well. It might help you understand a little more. Or use some static counter that you increase in the constructor and check in the destructor. - Some programmer dude

2 Answers

5
votes

throw makes a copy of the object, which is then destroyed automatically after catch. It is this destruction that you observe. The original heap-allocated object is indeed never destroyed.

3
votes

You actually have a memory leak, because the destructor that is called is not for the object allocated by new.

throw *(new A()); results in a copy of the object and you can see that the copy constructor is called. And this is the object that the destructor is called for at the end of the scope for catch.

You can check the live demo here.