I have the practice to use c++ assert to check if the program is running normally, such as this:
cv::Mat im = imread("pic.jpg")
assert(!im);
This would check if the image is read correctly. This is useful since the image might not be correctly placed in the expected directory, so we need to check. I feel that using assert
is convenient, but people say that using assert
would bring overhead to the program, and the suggestion is not using them. Why assert
will bring overhead ? What is the good practice to check in this case ?
First, assert()
is not an ordinary function. It is macro that looks similar to this:
#ifdef NDEBUG
#define assert(condition) ((void)0)
#else
#define assert(condition) /*implementation*/
#endif
and as you see it is only enabled and doing something when NDEBUG
is not defined. It is meant to be used to do extra checks on your program when you run in debug mode to help pinpoint errors (e.g. wrong arguments, invariants that don't hold, etc.) faster.
Assert itself probably doesn't cost that much performance if you use it as you shown but because of what I wrote above - it being debugging tool - might be used in many places of codebase. If conditions passed to assert are complex, sure it might take time to evaluate them (and your customers don't need to worry because this will only happen in debug mode, so they will be unaffected - with NDEBUG
all that overhead will go away).
You should not use assert()
to validate things you want always validated (also in non-debug mode). In this case it is correct to do:
cv::Mat im = imread("pic.jpg")
if (!im) {
/* handle error ... */
}