This code:
#include "stdafx.h"
#include <iostream>
using namespace std;
class singleTon
{
float testVal;
public:
singleTon()
{
cout << "Singleton created\n";
testVal = 0.0;
}
~singleTon()
{
cout << "Singleton deleted\n";
}
void setTest(float x)
{
testVal = x;
}
float getTest()
{
return testVal;
}
};
class myClass
{
singleTon s;
public:
myClass()
{
cout << "myClass created\n";
}
~myClass()
{
cout << "myClass deleted\n";
}
singleTon getSingleTon()
{
return s;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
myClass m;
m.getSingleTon().setTest(100);
cout << "\ngetting" << m.getSingleTon().getTest();
cout << "\nSetting:";
m.getSingleTon().setTest(200);
cout << "\ngetting" << m.getSingleTon().getTest();
getchar();
return 0;
}
After the first setTest()
:
m.getSingleTon().setTest(100);
The singleton class's destructor is getting called.
But, why?
My understanding was that it will still hold the singleton instance in class myClass
. I know, if I use heap allocation, it may work. But what is wrong with this style? Where is the issue?