Assert return value, but work anyway

As a rule, when I erase an element from a set, I want to claim that it was actually deleted: that is

assert(s.erase(e)); 

but then the item is not erased when installing NDEBUG. But if I write

 bool removed = s.erase(e); assert(removed); 

the compiler complains that 'remove' is not used when NDEBUG is installed.

How can I do it right?


In the end, I just created a utility method:

 inline void run_and_assert(bool b) { assert(b); } 

now i can say

 run_and_assert(s.erase(e)); 

Are there any flaws? It seems easier than luiscubal solution

+7
c ++ coding-style assert compiler-warnings boolean-expression
source share
2 answers

I wrote my own as a luiscubal sentence, but instead of the ugly #define, I made a short built-in method:

 inline void assert_always_execute(bool x) { assert(x); } 
0
source share

The first example is incorrect because the assert expression will be deleted when defining NDEBUG, so s.erase(e) will not be called at all.

The assert argument should NEVER have side effects.

The second approach is better, although the warning can be really annoying, but there are ways to turn off the warning .

Alternatively, you can find your own assert statement, which always executes code.

 #ifdef NDEBUG #define assert_always_execute(x) (x) #else #define assert_always_execute(x) assert(x) #endif 
+8
source share

All Articles