Reputation: 349
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#.
Upvotes: 1
Views: 2338
Reputation: 1939
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.
Upvotes: 1
Reputation: 30161
Maybe, but don't throw exceptions. You should anticipate I/O errors and swallow them or otherwise dispose of them without throwing.
Upvotes: 2