see the following code:
#include <iostream>
using namespace std;
struct T
{
~T()
{
cout << "deconstructor calling\n";
}
};
static T& get1()
{
static T x;
return x;
}
static T& get2()
{
static T& x = *new T;
return x;
}
int main()
{
get1();//calls the deconstructor
get2(); //dosent call the deconstructor
}
why get1
calls the deconstructor but get2
doesn't? as far as I know the static variables destroy when you terminate the program ! but why after calling get1
program calls the deconstrucor of the static variable?
I have a read similar the post at :
What is the lifetime of a static variable in a C++ function?
somebody says there that :"The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination."
this doesn't seem to be true here!