应该将输出操作放入析构函数吗?(Should one put output operations into a destructor?)

编程入门 行业动态 更新时间:2024-10-08 18:31:10
应该将输出操作放入析构函数吗?(Should one put output operations into a destructor?)

我有一个在程序执行期间收集和处理一些数据的类,我们称之为dataCollectionInterface 。 当程序终止(或者说: dataCollectionInterface对象超出范围)时,需要完成一些最终处理和输出(某些)收集的数据。

现在的问题是:我应该把这个最终处理和输出(到文件)放入dataCollectionInterface的析构dataCollectionInterface (或从析构函数中调用它)? 还是应该提供一个需要由主程序明确调用的公共成员例程( doFinalProcessing )?

将它放入析构函数会更加方便(在调用doFinalProcessing之后不需要担心数据调制的doFinalProcessing等),但是在处理输出操作中可能出现的异常方面是否有缺点?

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?

最满意答案

您不应该从析构函数中抛出任何异常 ,所以最好在公共函数中执行它,而不是在析构函数中执行,如果您的操作可以抛出异常并且您需要为它们执行异常处理。

虽然,如果你可以宁愿在析构函数中处理所有的异常而不把它们从析构函数中抛出,那么你也可以采用第一种机制,如果你能够可靠地这样做,我认为没有任何坏处。

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.

更多推荐

本文发布于:2023-07-30 14:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338785.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   放入   操作   put   operations

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!