Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly is the destructor called in C++

Tags:

c++

Consider following code

int i;

class A
{
public:
   ~A()
   {
       i=10;
   }
};

int foo()
{
   i=3;
   A ob;
   return i;
}

int main()
{
   cout << foo() << endl;
   return 0;
}

Since i is global, I thought the output of this program should be 10. ob, when it goes out of scope will call the destructor which should set value of i to 10.

like image 875
Avinash Avatar asked Jul 24 '14 07:07

Avinash


2 Answers

Local variables go out of scope, and their destructors are executed, after the function returns. Which means that by the time ~A() runs, the return value is already 3. In contrast, if you did this...

int foo()
{
   {
      i=3;
      A ob;
   }
   return i;
}

...ob would go out of scope and die before the return statement, and the result would be 10.

Extra scopes are often used this way with RAII-active types like scoped_lock, to go into some particular side-effect-ful state for only part of a function.

like image 110
Sneftel Avatar answered Sep 19 '22 14:09

Sneftel


int foo()
{
   i=3;
   A ob;
   return i;
} // <- ~A() is called here

~A() is called at the end of the function foo(), when ob goes out of scope. This is after the return value is calculated (i.e. a copy of i, with the value of 3 at that time).

In order for i to be set to 10 before the function exits, you would need to force ob to go "out of scope earlier". The simplest is to add an additional scope around A ob.

int foo()
{
   i=3;
   {
     A ob;
   } // <- ~A() is called here and sets i to 10
   return i;
}
like image 24
Niall Avatar answered Sep 18 '22 14:09

Niall