How can I assert() without using abort()?

后端 未结 6 1050
失恋的感觉
失恋的感觉 2020-12-08 20:06

If I use assert() and the assertion fails then assert() will call abort(), ending the running program abruptly. I can\'t afford that

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 20:29

    Here's what I have my in "assert.h" (Mac OS 10.4):

    #define assert(e) ((void) ((e) ? 0 : __assert (#e, __FILE__, __LINE__)))
    #define __assert(e, file, line) ((void)printf ("%s:%u: failed assertion `%s'\n", file, line, e), abort(), 0)
    

    Based on that, replace the call to abort() by a throw( exception ). And instead of printf you can format the string into the exception's error message. In the end, you get something like this:

    #define assert(e) ((void) ((e) ? 0 : my_assert (#e, __FILE__, __LINE__)))
    #define my_assert( e, file, line ) ( throw std::runtime_error(\
       std::string(file:)+boost::lexical_cast(line)+": failed assertion "+e))
    

    I haven't tried to compile it, but you get the meaning.

    Note: you'll need to make sure that the "exception" header is always included, as well as boost's (if you decide to use it for formatting the error message). But you can also make "my_assert" a function and only declare its prototype. Something like:

    void my_assert( const char* e, const char* file, int line);
    

    And implement it somewhere where you can freely include all the headers you require.

    Wrap it in some #ifdef DEBUG if you need it, or not if you always want to run those checks.

提交回复
热议问题