[boost] : asser库用法

基本用法

需要包含头文件#include <boost/assert.hpp>
assert库定义了两个断言宏

BOOST_ASSERT
BOOSE_ASSERT_MSG

第一种形式等价于assert宏, 断言表达式为真. 第二种形式允许断言失败是输出描述性字符串用于排错.
BOOST_ASSERT宏只在debug模式下生效, 在release模式下不会编译, 不会影响运行效率.

#include <iostream>
#include <cstring>
#include <boost/assert.hpp>
using namespace std;

double func(int x)
{
    BOOST_ASSERT_MSG(x != 0, "divided by zero");
    return 1.0 / x;
}

void case1()
{
    BOOST_ASSERT(16 == 0x10); // 断言成立
    // BOOST_ASSERT(string().size() == 1); // 断言失败, 抛出异常

    // func(0); // 导致断言失败, 抛出异常

    int len;
    BOOST_ASSERT(len = strlen("123"));
    assert(len == 3);
}

int main()
{
	case1();
	return 0;
}

BOOST_ASSERT(string().size() == 1);断言失败会输出一下信息:

assert.cpp:15: void case1(): Assertion `string().size() == 1' failed.

func(0)导致断言失败会输出以下信息:

assert.cpp:8: double func(int): Assertion `(x != 0)&&("divided by zero")' failed.

禁用断言

如果在头文件<boost/assert.hpp>之前定义宏BOOST_DISABLE_ASSERT会导致BOOST_ASSERT自动失效, 但标准的assert宏不受影响

#define BOOST_DISABLE_ASSERT
#include <boost/assert.hpp>

double func2(int x)
{
    BOOST_ASSERT(x != 0 && "divided by zero"); // 失效
    cout << "after BOOST_ASSERT" << endl;

    assert(x != 0 && "divided by zero"); // 有效
    cout << "after" << endl;

    return 1.0 / x;
}

扩展用法

如果在头文件<boost/assert.hpp>之前定义宏BOOST_ENABLE_ASSERT_HANDLER, 将不再等同于assert宏, 断言表达式无论在debug还是release模式都将被求值, 如果断言失败自动调用assertion_failed()或者assertion_failed_msg(), 这相当于提供一个错误处理hanlder.
注意: 用户必须实现assertion_failed()函数和assertion_failed_msg().

#include <iostream>
#include <cstring>
#include <boost/format.hpp>

#define BOOST_ENABLE_ASSERT_HANDLER
#include <boost/assert.hpp>
using namespace std;

double func(int x)
{
    BOOST_ASSERT_MSG(x != 0, "divided by zero");
    return 1.0 / x;
}

namespace boost 
{
	void    assertion_failed(char const*, char const*, char const*, long) {}
	void assertion_failed_msg(char const * expr, char const * msg, 
	                          char const * function, 
	                          char const * file, long line)
	{
	    boost::format fmt("Assertion failed!\nExpression: %s\n"
	                      "Function: %s\nFile: %s\nLine: %ld\n"
	                      "Msg: %s\n\n");
	    fmt % expr% function% file% line %msg;
	    cout << fmt;
	}
}

int main()
{
	func(0);
	return 0;
}

断言失败输出:

Assertion failed!
Expression: x != 0
Function: double func(int)
File: assert.cpp
Line: 11
Msg: divided by zero
posted @ 2017-09-05 16:51  moon1992  阅读(310)  评论(0编辑  收藏  举报