assert的陷阱

来源:互联网 发布:linux基础知识试题 编辑:程序博客网 时间:2024/04/30 11:12
【原文写于5 January 2007,注】

 

bool setValue(int & i) { i = 1; return true; }

int i = 0;
assert(setValue(i));

上边的代码,在debug版中能正常运行,但在release中,运行后i的值仍为0,setValue(i)没有执行
assert,包括MFC的ASSERT,在release中“形同虚设”,导致setValue(i)也虚设了
因此,使用assert要非常小心,只能assert简单的判断语句

要避免这样的问题还有一个办法,MFC提供VERIFY,VERIFY中的语句能够正常执行,只是不会检查值是否true。
C runtime library中没找到类似的功能

from MSDN:
In the release version of MFC, VERIFY evaluates the expression but does not print or interrupt the program. For example, if the expression is a function call, the call will be made