RAII vs. exceptions

后端 未结 7 1376
小鲜肉
小鲜肉 2021-01-29 21:54

The more we use RAII in C++, the more we find ourselves with destructors that do non-trivial deallocation. Now, deallocation (finalization, however you want to call it) can fail

7条回答
  •  悲&欢浪女
    2021-01-29 22:42

    What are the reasons why your destruction might fail? Why not look to handling those before actually destructing?

    For example, closing a database connection may be because:

    • Transaction in progress. (Check std::uncaught_exception() - if true, rollback, else commit - these are the most likely desired actions unless you have a policy that says otherwise, before actually closing the connection.)
    • Connection is dropped. (Detect and ignore. The server will rollback automatically.)
    • Other DB error. (Log it so we can investigate and possibly handle appropriately in the future. Which may be to detect and ignore. In the meantime, try rollback and disconnect again and ignore all errors.)

    If I understand RAII properly (which I might not), the whole point is its scope. So it's not like you WANT transactions lasting longer than the object anyway. It seems reasonable to me, then, that you want to ensure closure as best you can. RAII doesn't make this unique - even without objects at all (say in C), you still would try to catch all error conditions and deal with them as best as you can (which is sometimes to ignore them). All RAII does is force you to put all that code in a single place, no matter how many functions are using that resource type.

提交回复
热议问题