This post is a note for Modern C++ Libraries in Pluralsight.
An Assertion may be a function, but usually a macro, that brings your application to an immediate standstill if an assumption is broken.
Assertions document the assumptions such that those assumptions can be validated usually at run time, but also increasingly at compile time.
Check pointers before using them (at run time):1assert(pointer);
Confirm the validity of some input at the boundary of application or component (at run time):
Confirm some expressions at compile time (no need to execute)1static_assert(sizeof(float) == 4, "I can’t float like that!");
Static or compile time Assertions are checked staticially during build. And Runtime Assertions are typically conditionally complied and included owning debug builds and stripped out of release or free builds.
Runtime Assertions must not include expression that the application relies upon. It should not change the application state in any way.
The definition of the macro
assert depends on another macro,
NDEBUG, which is not defined by the standard library.
NDEBUG is defined as a macro name at the point in the source code where
<cassert> is included, then
assert does nothing.
NDEBUG is not defined, then
assert checks if its argument (which must have scalar type) compares equal to zero. If it does,
assert outputs implementation-specific diagnostic information on the standard error output and calls std::abort.
assert is a function-like macro, commas anywhere in condition that are not protected by parentheses are interpreted as macro argument separators. Such commas are often found in template argument lists:
Performs compile-time assertion checking
Since message has to be a string literal, it cannot contain dynamic information or even a constant expression that is not a string literal itself. In particular, it cannot contain the name of the template type argument.
Verify behaves exactly the same as Assert in debug builds. Indeed it is an Assertion. But in release builds it drops the verification, but keeps the expression.
Unlike runtime Assertions the Verify macro is used for those cases where the expression is essential to the applications operation and cannot simply be stripped out of release builds.
Trace macro is to provide formatted output for the debugger to display, but that can be stripped out of release builds.
Following code works only in VC++:
Assertions are useful, however,
TRACE can be repalced by other logging libaries.