MFC ASSERT宏使用详解

来源:互联网 发布:网上报名系统源码 编辑:程序博客网 时间:2024/06/10 22:09

摘自msdn 2001版:

ASSERT( booleanExpression)

Parameters

booleanExpression

Specifies an expression (including pointer values) that evaluates to nonzero or 0.

Remarks

Evaluates its argument. If the result is 0, the macro prints a diagnostic message and aborts the program. If the condition is nonzero, it does nothing.

The diagnostic message has the form

assertion failed in file <name> in line <num>

where name is the name of the source file, andnum is the line number of the assertion that failed in the source file.

In the Release version of MFC, ASSERT does not evaluate the expression and thus will not interrupt the program. If the expression must be evaluated regardless of environment, use theVERIFY macro in place of ASSERT.

Note   This function is available only in the Debug version of MFC.

Example

// example for ASSERTCAge* pcage = new CAge( 21 ); // CAge is derived from CObject.ASSERT( pcage!= NULL )ASSERT( pcage->IsKindOf( RUNTIME_CLASS( CAge ) ) )// Terminates program only if pcage is NOT a CAge*.
这里有个地方要特别注意,就是ASSERT宏仅能用于Debug环境,在Release环境下,它是啥也不干的:
mfc源代码中是这样定义的:
如果是Debug版,定义代码如下:
 
#define THIS_FILE          __FILE__#define ASSERT(f) \do \{ \if (!(f) && AfxAssertFailedLine(THIS_FILE, __LINE__)) \AfxDebugBreak(); \} while (0) \
如果是Release版本,定义代码如下:
#define ASSERT(f)          ((void)0)
发现了吗?如果是Release版,ASSERT宏不管你的f参数是啥,都给你搞成"(void)0",这意味这千万不要在ASSERT中放入一个函数调用,如:“ASSERT(((CDatasetVector*)pDTTemp)->CreateField(fldInfo))”你本想用ASSERT判定CreateField函数的返回值,Debug版是没问题的,但是到了Release版,这一行代码啥也没做!也就是说你的CreateField函数根本就没有被编译,当然也就谈不上被执行啦!