1

Is it a good idea to log output to a file in a C++ class destructor? My use case is a simulator where I have a logging class that logs to an in-memory data structure and then dumps it all into a file when it is destructed.

This is similar to the question here (C# class: Do logging / housekeeping, should I use a destructor?), but my question deals with standard non garbage-collected C++, not C#.

Community
  • 1
  • 1
Anirudh
  • 239
  • 3
  • 11
  • 2
    There's no reason why you couldn't do that. You must not throw an exception from a destructor, but otherwise you can do pretty much everything you want, including things like e.g. releasing resources/memory/locks, or well, logging that an object was destroyed. – Damon Apr 15 '15 at 18:17
  • It depends on how you are going to set up your logging. Are you using standard IO (either cstdio or iostream) ? Are you using a framework ? Something more elaborated ? It shouldn't be problematic to log in destructors, but make sure that you don't allow your logger to throw exceptions (in particular, don't handle IO errors when logging this way) – Alexandre C. Apr 15 '15 at 18:24

2 Answers2

2

Maybe, but don't throw exceptions. You should anticipate I/O errors and swallow them or otherwise dispose of them without throwing.

Kevin
  • 28,963
  • 9
  • 62
  • 81
1

Well you CAN do it but I would not recommend it.

First of all, it is not a good idea to pull weird design stunts like that. You will probably end up obfuscating your code. Destructor's main purpose of existence is deallocating resources that your class has allocated, like files or memory.

Another problem is exceptions. If you try to add an I/O operation in your destructor and something goes wrong, you won't be able to see it. So let's say you have this huge application where the logs are of vital importance. You may miss a log. Or even worse, have unexpected data on a log.

Anyway, I recommend you add a bool Shutdown() function to your class. That's what I do in cases like that. That way you control what's going on.

Hope I helped.

TheCrafter
  • 1,909
  • 2
  • 23
  • 44
  • Many objects (including in the form of smart pointers) after creation are transferred to the full ownership of other objects, lists, engines. And none of the new owners will call Shutdown() for such objects before destroying them. – pier_nasos Dec 03 '21 at 13:54
  • @pier_nasos well sure but the question was whether or not it is a good idea to do logging (specifically, on a file) on a destructor. And it's not. Of course, my advice now (6 years later) would be different. I'd suggest to create something like a "logging queue" and just queue a log on the destructor. The queue will handle the I/O operations at a later time. – TheCrafter Dec 28 '21 at 21:36