My instructor says we don't need to delete a singleton object created in the heap because when out of scope its memory is released and auto deletes.
Is it that the compiler treats static objects differently that we don't need to worry about deleting this object from the heap?
In the code below, I think it's the pointer that goes out of scope in main and not the object in the heap itself, but at some point the destructor of the object should be called if indeed the memory is released for this object?
I also tried adding member function DeleteObject in main but I can't see the destructor of the object in heap being called.
but still can't see the destructor show the message on screen.
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton* GetInstance();
void Show() { cout << "Single object"; }
void DeleteObject();
~Singleton();
private:
static Singleton* psingleton;
Singleton();
};
void Singleton::DeleteObject() {
delete psingleton;
}
Singleton::~Singleton() {
cout << "\n\nAt Destructor";
}
Singleton* Singleton::psingleton = 0;
Singleton::Singleton()
{
//do stuff
}
Singleton* Singleton::GetInstance() {
if (psingleton = NULL ) {
psingleton = new Singleton();
}
return psingleton;
}
int main()
{
Singleton::GetInstance()->Show();
Singleton::GetInstance()->DeleteObject();//another try
return 0;
}
Would expect the object destructor to show a message on screen because it's called.