Access violation on unusual program termination (C++)
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());
开发者_JAVA技巧 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.
cout
is a global object. Your singleton instance (defined as static in the getInstance
static 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 cout
object is destructed before your SingletonLogClass
is. As the destructor of your SingletonLogClass
logs something, it cannot use anymore cout
(whereas printf
is fine).
The difference in behaviour when the program is terminated normally (pressing enter) and thus exiting the main
function, 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.
精彩评论