PapaDiHatti
PapaDiHatti

Reputation: 1921

How the destructor is called for heap object without delete operator?

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

Upvotes: 3

Views: 215

Answers (2)

P.W
P.W

Reputation: 26800

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.

Upvotes: 3

yuri kilochek
yuri kilochek

Reputation: 13486

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.

Upvotes: 5

Related Questions