I have not found answer for this question but I'm almost 100% sure there is laying out somewhere.
I have a normal C++ class, and I'm using a 3rd party logging system. Unfortunately I have 2 requirements and 3 facts which I can't match:
Requirements:
Facts:
pthread_mutex_lock
.Here is the code:
class myClass {
public:
myClass() {}
~myClass() {
LOG << "Destructor called!";
}
};
int main() {
myClass c;
sleep(1);
return 0;
}
When program finishes, there is a segmentation fault because of the LOG
command (i.e: if I remove it, there is no segfault).
In normal circumstances I'd need this log function to show when myClass
is destructed, so here comes the straightforward question:
Can I somehow detect in the destructor of a class (myClass) if program is terminating (or something else is the reason for destruction)?
Can I somehow detect in the destructor of a class (myClass) if program is terminating
Yes, if the instance has static storage. You can register a function that will be executed during destruction of static objects using std::atexit
. This function can be used to set a namespace scope variable that signifies whether the program is exiting or not. The destructor of your class can check the state of that variable.
You must make sure that the instance whose destructor relies on the variable is created before std::atexit
is called.