Path: csiph.com!news.swapon.de!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:34:04 +1300 Lines: 46 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 jZmGEFcjcIxMKBRgaKpfwQBi0b7zU1TVGTfVW53OMUHr1Q2ZnM Cancel-Lock: sha1:lIUMlmt4R2lN2vhdYThkmNzp+E8= 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++:41208 Mr Flibble wrote: > On 24/02/2016 00:00, Ian Collins wrote: >> 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. > > If stack unwinding can be dangerous in the face of a detected logic > error (and I agree it is technically possible) then why can > std::vector::at() throw an exception in the first place? In fact why > does std::logic_error exist at all? Because std::vector is designed to do so? If for an example an invalid pointer triggers an assert, I would want to know how this condition occurred, an assert and a core would give me the best chance of doing so. Even if the alternative exception captured the stack, it wouldn't help if the bad data came from another thread. Use exceptions where recovery is an option, asserts where it isn't. > Following your logic to its ultimate conclusion there should exist a > proposal to deprecate/remove std::logic_error and exceptions derived > from it from C++. I think you lost the way somewhere. std::logic_error has its place, but that place isn't as a substitute for assert. -- Ian Collins