Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Ian Collins Newsgroups: comp.lang.c++ Subject: Re: asserts considered harmful Date: Wed, 24 Feb 2016 13:00:29 +1300 Lines: 31 Message-ID: References: <8_2dnQWwaKOXRlHLnZ2dnUU7-dudnZ2d@giganews.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: individual.net wJNkGJ54//sv0YLXRiEKxg1O1sUTSropC+Erotoy/gRGD+kO37 Cancel-Lock: sha1:r1S1gY6AGdLynhwGnP7HAgr57d0= User-Agent: Mozilla/5.0 (X11; SunOS i86pc; rv:17.0) Gecko/17.0 Thunderbird/17.0 In-Reply-To: Xref: csiph.com comp.lang.c++:41203 Alf P. Steinbach wrote: > On 23.02.2016 23:19, Mr Flibble wrote: >> Code containing asserts will behave differently depending on whether or >> not the macro NDEBUG is defined. This is dangerous as it may result in >> undetected bugs in a release build manifesting as undefined behaviour >> that doesn't cause a straight crash but does something more serious. > > Well, you can define a wrapper that throws an exception in NDEBUG > (a.k.a. “release”) mode, then preferably a “hard exception” that has > maximum chances of propagating all the way up to `main`. > > The main problem with that, as I see it, is that cleanup via stack > unwinding can be dangerous when an assertion has failed. Not only that, but unless you can capture enough context, it offers little help in diagnosing the cause. I much prefer to have a decent core dump to analyse than an exception report. I guess things are different on platforms that lack support for cores, but even in embedded systems, you are often better off rebooting than trying to handle an unexpected condition. The discussion should be around where to use assert and where to throw an exception, forget about NDEBUG. I'm guessing the former is less frequent in most code, but when it is used, the options for recovery are sparse and the code to handle it nonexistent. So swapping an assert for an exception in production builds may be even more dangerous. My advice is to use asserts sparingly and keep them in! -- Ian Collins