现在的位置: 首页 > 综合 > 正文

了解C++11(四)—— 断言(assertion)

2014年09月02日 ⁄ 综合 ⁄ 共 1221字 ⁄ 字号 评论关闭
文章目录

断言(assertion)主要用于调试中,帮助我们快速定位那些违反了某些前提条件的程序错误。

一、运行时断言

使用assert宏进行运行时断言。

#include <cassert>

char * ArrayAlloc(int n)
{
    assert(n > 0);
    return new char [n];
}

int main()
{
    char *a = ArrayAlloc(0); // Assertion failed: n > 0

    return 0;
}

通常在程序发布时会禁用断言,避免程序非正常退出, 因为用户不愿意看到这个。通过定义NDEBUG宏可以做到这个,因为assert宏大致是这样实现的:

#ifdef NDEBUG
// If not debugging, assert does nothing.
#define assert(x)	((void)0)

#else // debugging enabled 

#define assert(e)    ((e) ? (void)0 : _assert(#e, __FILE__, __LINE__))

#endif	// NDEBUG

二、预处理断言

#if BUFFER_BLOCK_SIZE < 4
	#error “BUFFER_BLOCK_SIZE must not be less than 4” //缓冲区块的最小值不允许小于4 
#endif

假设BUFFER_BLOCK_SIZE被定义为3,则编译时会输出如下错误信息:

error: #error“BUFFER_BLOCK_SIZE must not be less than 4”

三、静态断言

c++11引入static_assert来实现编译期断言,称为静态断言。因为运行时断言必须要运行程序,并且必须执行到assert相关的代码路径才能发现问题。相比较而言,编译期断言则能更早更容易的发现问题。

static_assert有2个参数,第1个是断言表达式,第2个是警告信息字符串。

static_assert(constant-expression , string-literal);

In a static_assert-declaration the constant-expression shall be a constant expression that can be contextually converted to bool.If
the value of the expression when so converted is true, the declaration has no effect. Otherwise, the program is ill-formed, and the resulting diagnostic message shall include the text of the string-literal.

Example:

static_assert(sizeof(long) >= 8,
    "64-bit code generation required for this library.");

学习资料: 《深入理解C++11:新特性解析与应用》

抱歉!评论已关闭.