Note that there are some explanatory texts on larger screens.

plurals
  1. POIs using assert() in C++ bad practice?
    primarykey
    data
    text
    <p>I tend to add lots of assertions to my C++ code to make debugging easier without affecting the performance of release builds. Now, <code>assert</code> is a pure C macro designed without C++ mechanisms in mind.</p> <p>C++ on the other hand defines <code>std::logic_error</code>, which is meant to be thrown in cases where there is an error in the program's logic (hence the name). Throwing an instance might just be the perfect, more C++ish alternative to <code>assert</code>.</p> <p>The problem is that <code>assert</code> and <code>abort</code> both terminate the program immediately without calling destructors, therefore skipping the cleanup, whereas throwing an exception manually adds unnecessary runtime costs. One way around this would creating an own assertion macro <code>SAFE_ASSERT</code>, which works just like the C counterpart, but throws an exception on failure. </p> <p><strong>I can think of three opinions on this problem:</strong></p> <ul> <li><em>Stick to C's assert.</em> Since the program is terminated immediately, it does not matter whether changes are correctly unrolled. Also, using <code>#define</code>s in C++ is just as bad.</li> <li><em>Throw an exception and catch it in main()</em>. Allowing code to skip destructors in any state of the program is bad practice and must be avoided at all costs, and so are calls to terminate(). If exceptions are thrown, they must be caught.</li> <li><em>Throw an exception and let it terminate the program.</em> An exception terminating a program is okay, and due to <code>NDEBUG</code>, this will never happen in a release build. Catching is unnecessary and exposes implementation details of internal code to <code>main()</code>.</li> </ul> <p>Is there a definitive answer to this problem? Any professional reference?</p> <p><strong>Edited:</strong> Skipping destructors is, of course, no undefined behaviour. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload