Search code examples
c++destructorterminate

C++ detect program ending in destructor


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:

  1. Log something in destructor
  2. Handle the program termination clean (without crash)

Facts:

  1. 3rd party logging system crashes on program termination, because it calls pthread_mutex_lock.
  2. I don't want to change this logging system
  3. I also don't want to deepdive into it

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)?


Solution

  • 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.