2

I have some code that is in a c++ destructor, but I want it to do something different than normal if it is being destructed due to application exiting as opposed to a regular destruction.

Is there a way to do this?

More info: I have a logger object that if already destructed won't be able to log, though in the destructor for another object, it makes a logging call. I figure if in destruction, I can just skip log calls or reopen the logger if needed. This question is based off an inability to control the order of destruction. If the logger was destructed last, I wouldn't have this problem.

More Info 2: This application is actually less of an application and more of a dll loaded into another application. Though optimally a solution would work with exes and dlls.

csm10495
  • 569
  • 6
  • 12
  • 2
    Objects are destructed in the opposite order they're constructed in, so you could just make your logger object first, right? To the titular question, I don't believe there is a way to know, you would have to have your app track it yourself. – Tas Jul 23 '19 at 04:51
  • 2
    Depends on how the application is terminating. C style abort(), exit() etc. do not run destructors at all (and I would recommend avoiding the atexit and signal handlers if possible). Destructors get called if containing block is exited via return or exception, so you could do what Tas said. You can also detect if an object is being destructed because of exception in flight by using std::uncaught_exception() from . – Tronic Jul 23 '19 at 05:14
  • Singleton pattern is not really a solution, it only turns it into a bigger problem (adding hard-to-predict construction time). If the order matters, make a stack-bound object inside main() or other function/object. Everything defined after that object is constructed after and destroyed before (because destruction order is exact reverse of construction). – Tronic Jul 23 '19 at 05:19
  • @Scheff -- the construction order of global objects **defined in different translation units** is **unspecified**. Within a translation unit global objects are constructed in order of their definition. – Pete Becker Jul 23 '19 at 13:30
  • Added some more details. This is actually in a dll that has been loaded by the application. – csm10495 Jul 23 '19 at 13:58
  • I am confident that you don’t want this—if you’re doing such complicated things during static destruction, what’s to say you can’t have the logger created and destroyed several times therein, rendering the “exiting?” test meaningless. That said, you could just set such a flag in the destructor for the last object constructed (which will of course trigger upon unloading as well). – Davis Herring Jul 23 '19 at 23:49
  • To me this ask makes sense. I have a (boost) logger that is getting destructed before other things that log on destruction. I either want to skip logging in that case to not crash, or somehow get the logger to go last. – csm10495 Jul 24 '19 at 14:26

0 Answers0