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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With