0

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!

Community
  • 1
  • 1
MEMS
  • 617
  • 1
  • 6
  • 11
  • 1
    Why would the second one ever call the destructor. It's created using new, with no corresponding delete. It's a memory leak! You are also assigning the newed object to a reference, meaning it's no longer possible to get it's address to call delete. – Paul Rooney Feb 03 '17 at 11:35

2 Answers2

6

get1() is not calling ~T(). The simple way of proving it is calling get1() multiple times:

int main()
{
    get1();
    get1();
    get1();
    get2();  
    get2();  
    get2();  
}

The above code snippet will only display "deconstructor calling" once.

coliru example


why get1 calls the deconstructor but get2 doesn't?

The destructor call you're seeing happens at the end of the program, when the static T x defined in get1() gets destroyed.

The x defined in get2() does not get destroyed automatically because it is heap-allocated. You need to delete it or, better yet, use an std::unique_ptr.

coliru example


BTW, the correct term is "destructor".

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
3

why get1 calls the deconstructor but get2 doesn't?

Note the difference between get1() and get2(). The static variable in get1() is of type T, when it is destructed at program termination, the destructor of T will be invoked.

The static viariable in get2() is of type T& (i.e. a reference to T) and initialized from an object constructed via new. When it's destructed at program termination, the destructor of T won't be invoked. This is not special for static variable, it's true for local variable too. The destruction timings are different but the behaviors are same; the constructed object is leaked.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405