Boosst.assert库的简单尝试

对比C++标准库中的assertBoost.assert强化了原始的运行时assert宏,static_assert库提供了静态断言(编译期诊断),而lightweight_testtest库则构建了完整的单元测试框架。

这里写的是运行时assert

基本用法

assert库定义了两个断言宏

#define BOOST_ASSERT(expr)                            assert(expr)
#define BOOST_ASSERT_MSG(expr, msg)         assert((expr) && (msg))

对于第一种BOOST_ASSERT和标准库中的assert一样,第二种形式则允许断言失败时输出描述性字符串(msg)。

例如:

#include <boost/assert.hpp>

int main()
{
    int a = 10;
    BOOST_ASSERT(a == 10);
    BOOST_ASSERT_MSG(a != 10, "a is equal to 10");          // 断言为假,输出 "a is equal to 10"
    return 0;
}

禁止断言

在文件开头定义BOOST_DISABLE_ASSERTS会禁用boost.assert库,而标准的assert宏不会受到影响。

例如:

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

int main()
{
    int a = 10;

    // 下面两个将会失效
    BOOST_ASSERT(a == 10);
    BOOST_ASSERT_MSG(a != 10, "a is equal to 10");  
    return 0;
}

拓展用法

这是我觉得最有用的一种用法。如果断言失败,会发生一个断言失败的函数调用boost::assertion_failed()或者assertion_failed_msg()相当于提供了一个错误处理handler。可以在boost名称空间里重新自定义这两个函数。

namespace boost 
{
    void assertion_failed(char const* expr, char const* function, char const* file, long line);
    void assertion_failed_msg(char const* expr, char const* msg, char const* function, char const* file, long line);
}

参数:
1. expr – 是断言的表达式
2. function – 断言所在的函数
3. file – 文件路径
4. line – 错误代码的行号
5. msg – 错误提示信息(BOOST_ASSERT_MSG所用)

例如:

#define BOOST_ENABLE_ASSERT_HANDLER         // 启用handler
#include <iostream>
#include <boost/assert.hpp>
#include <boost/format.hpp>
using namespace std;

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;
    }
}

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

int main(int argc, char const *argv[])
{
    func(0);
    return 0;
}

运行结果:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值