Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one put output operations into a destructor?

Tags:

c++

class

I've got a class that collects and processes some data during the execution of the program, let's call it dataCollectionInterface. When the program terminates (or rather: a dataCollectionInterface object goes out of scope) some final processing and output of (some of) the collected data needs to be done.

The question now is: should I put this final processing and output (to files) into the destructor of dataCollectionInterface (or call it from within the destructor)? Or should I provide a public member routine (doFinalProcessing) that needs to be explicitly called by the main program?

Putting it into the destructor would be a lot more convenient (no need to worry about safeguards against data modulation after a call to doFinalProcessing etc.), but are there downsides, e.g. with respect to the handling of possible exceptions from the output operations?

like image 357
janitor048 Avatar asked Sep 14 '25 00:09

janitor048


2 Answers

You should not be throwing any exceptions from the destructor, So better to do it in a public function, rather than the destructor if your operations can throw exceptions and you need to do the exception handling for them.

Though, If you can rather handle all your exceptions within the destrucotr itself without throwing them out from the destructor, then you might go for the first mechanism as well, I see no harm if you can reliably do so.

like image 193
Alok Save Avatar answered Sep 16 '25 18:09

Alok Save


A destructor cannot fail. Thus, you should not put any operations which might fail (and output can fail) in a destructor; what do you do if it fails.

There are exceptions, when the operation isn't really relevant to the overall functionality of the program (logging output, for example), or when it is a safeguard (ofstream will close the file in the destructor, ignoring any errors), or when it is part of an operation which will be later "annulled": a non-committed transation may close an output file, for example, knowing that because the transaction is not committed, the file will later be deleted. But they are just that: exceptions.

like image 22
James Kanze Avatar answered Sep 16 '25 18:09

James Kanze