一、使用断言Assertion的几个原则
1.Use Assertion  to  Check a  Single  Item At a Time.
每次只检查一个条目。
我们使用断言,就是希望能够将错误暴露出来。如果在一个断言里同时检查多个条目,这样在出错的时候,你无法知道究竟是哪个条目出错了。
看看下面的代码
Debug.Assert( iSize > 0 &&  NULL != m_pReference)
如果这个时候断言出错,你知道是iSzie出错还是m_pReference了?
所以,应该像下面这样:
Debug.Assert( iSize > 0);
Debug.Assert( NULL 
!= m_pReference);
2. Assert the Conditions Completely.
检查所有可能的情况。
要检查所以可能的情况,不然,如果出现了你没有检查的情况,错误仍然没法暴露出来。
3. Assert against Specific Values.
和特定的值比较。
看看下面的代码。
Debug.Assert( nCount );
碰到这样的代码,我们应该像下面这样写:
Debug.Assert( nCount > 0 );
二、对哪些进行断言?
1. Check Parameters passed into the method 检查方法接受的参数
2. Check Return Values 检查返回值
3. Check the Assumption
三、Native Assert
C/C++有以下几种断言:
assert  _ASSERT _ASSERTE

1.assert
assert is used by C Runtime. So it's portable for all C platform. Besides, it's declared in ASSERT.H.
If your application is a console application, then if assert is triggered, then the error message will be written into stderr. If your application is Window form application(GUI Application), then a message box will pop-up when the assert is triggered.

2. _ASSERT _ASSERTE
This is only for Window, not protable.
These two are declared in CRTDBG.h.

When using these two types of assert, here're the things I listed you need to take care of.
   - when output the file name, there's a limitation for file length which could not be greater than 60. Otherwise you will have no idea about which file causes.
   - Since assert use the stderr or message box to output the error message, it might cause problem if your component is a COM Server or window service. The worst is that it will cause your application hang.



posted on 2008-06-23 21:51  xiaxi  阅读(434)  评论(0)    收藏  举报