The following minimum code examples runs fine when it is terminated normally (by pressing enter):
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
class SingletonLogClass
{
private:
SingletonLogClass() {}
public:
~SingletonLogClass()
{
LogMessage("~SingletonLogClass()");
}
static SingletonLogClass& getInstance(void)
{
static SingletonLogClass inst;
return inst;
}
void LogMessage(string msg)
{
//printf("%s\n", msg.c_str());
cout << msg << endl;
}
};
int main(int argc, char* argv[])
{
SingletonLogClass::getInstance().LogMessage("This is a message");
getchar();
return 0;
}
When I terminate the program by closing the console window it depends on the implementation of the LogMessage function. If it’s implemented using printf everything is fine. But when it’s implemented using cout I get an access violation.
Can someone explain this?
What exactly happens when the program is terminated by closing the console window?
Why does it work with printf but not with cout?
I’m working with VC++ 2010.
coutis a global object. Your singleton instance (defined as static in thegetInstancestatic member function) is also a global object.In C++, you cannot have control over the order of construction, neither destruction of global objects. As such, it is possible that the
coutobject is destructed before yourSingletonLogClassis. As the destructor of yourSingletonLogClasslogs something, it cannot use anymorecout(whereasprintfis fine).The difference in behaviour when the program is terminated normally (pressing enter) and thus exiting the
mainfunction, and when the program is terminated abruptly by closing the shell comes from the order of destruction of globals. You cannot have control over the order of destruction of global objects.