找回密码
 注册
搜索
查看: 3771|回复: 0

[转帖] ASSERT()有什么作用

[复制链接]
发表于 2003-4-2 20:09:53 | 显示全部楼层 |阅读模式
程序一般分为Debug版本和Release版本,Debug版本用于内部调试,Release版本发行给用户使用。5 a/ X& H6 X( g6 |, }9 F
    断言assert是仅在Debug版本起作用的宏,它用于检查“不应该”发生的情况。以下是一个内存复制程序,在运行过程中,如果assert的参数为假,那么程序就会中止(一般地还会出现提示对话,说明在什么地方引发了assert)。
; Q9 E- Z  b. v: v5 ^& } //复制不重叠的内存块- l3 c: X9 f2 i. P7 b0 v
void  memcpy(void *pvTo, void *pvFrom, size_t size)6 Y( N( v, W* J. R/ Q  w
{
. I/ I0 Z4 H$ `3 J, V  void *pbTo = (byte *) pvTo;# D2 E6 D4 g7 Z6 W* S3 Y
  void *pbFrom = (byte *) pvFrom;
! k: L( w' {- n/ V! S+ U  assert( pvTo != NULL  &&  pvFrom != NULL );9 B6 ]  m: r9 |4 t
  while(size - - > 0 )
- _4 E7 z% x3 A! K7 x/ p   *pbTo + + = *pbFrom + + ;
5 M/ A5 o0 P- D+ X& \" ]4 \  return (pvTo);; h& _. q& @; O& F2 f9 n
}( }& n7 S2 b( {- |
assert不是一个仓促拼凑起来的宏,为了不在程序的Debug版本和Release版本引起差别,assert不应该产生任何副作用。所以assert不是函数,而是宏。程序员可以把assert看成一个在任何系统状态下都可以安全使用的无害测试手段。
0 \7 m+ l# U3 j/ w% A, k以下是使用断言的几个原则:& \. n- ^! U- O* d- Q, U; [  X4 |1 n. U
1)使用断言捕捉不应该发生的非法情况。不要混淆非法情况与错误情况之间的区别,后者是必然存在的并且是一定要作出处理的。
0 ~5 p+ L$ u+ H; n3 i' k, T2)使用断言对函数的参数进行确认。
$ g2 X8 |1 F4 k: T$ E3)在编写函数时,要进行反复的考查,并且自问:“我打算做哪些假定?”一旦确定了的假定,就要使用断言对假定进行检查。
" k6 f0 d$ w- c6 q  O# M4)一般教科书都鼓励程序员们进行防错性的程序设计,但要记住这种编程风格会隐瞒错误。当进行防错性编程时,如果“不可能发生”的事情的确发生了,则要使用断言进行报警。
. L2 m2 V. t* e& a( O以下是MSDN对ASSERT的说明:
0 g6 h2 W" I) G$ VASSERT( booleanExpression ). G6 F# y7 I$ X: w
Parameters3 \5 h% g; X) X) B
booleanExpression
7 b) d/ S6 x  I6 vSpecifies an expression (including pointer values) that evaluates to nonzero or 0.8 _6 K/ l9 C2 J
Remarks
/ g% ~7 k, N  c9 UEvaluates 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.1 L( q# s6 s* s" F
The diagnostic message has the form( e. e. B  V6 W
assertion failed in file <name> in line <num>
5 Q4 u: |2 w3 G% k: `- Nwhere name is the name of the source file, and num is the line number of the assertion that failed in the source file.4 P& e0 [. F" v) q- h# f6 y; Q$ i7 z, K
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 the VERIFY macro in place of ASSERT.8 m6 v; ?  X! E$ z' c
Note   This function is available only in the Debug version of MFC.% Z7 O  @2 d. T1 |  d0 K( m
Example
0 o" H: Z; [/ @% ]' ?4 w// example for ASSERT
4 e: c% B; e% v6 g& [3 `CAge* pcage = new CAge( 21 ); // CAge is derived from CObject.+ W4 ]: M3 @; j% ^: K' D
ASSERT( pcage!= NULL )
$ A  Q; f6 |- J4 t# gASSERT( pcage->IsKindOf( RUNTIME_CLASS( CAge ) ) )
  @1 c2 ?: ]9 f; s7 @// Terminates program only if pcage is NOT a CAge*.
8 {5 |2 H) m2 E) v! I, W- a
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|宁德市腾云网络科技有限公司 ( 闽ICP备2022007940号-5|闽公网安备 35092202000206号 )

GMT+8, 2025-5-5 05:02 , Processed in 0.014960 second(s), 15 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表