设为首页 加入收藏

TOP

调试秘笈之运行时的错误(五)
2013-04-24 12:13:08 来源: 作者: 【 】 浏览:947
Tags:调试 秘笈 行时 错误

 

    {

    std::ostringstream ss;

    ss 《 "SCPP assertion failed with message '" 《 message

    《 "' in file " 《 file_name 《 " #" 《 line_number;

    what_ = ss.str();

    }

    }

    #endif // SCPP_THROW_EXCEPTION_ON_BUG

    void SCPP_AssertErrorHandler(const char *file_name, unsigned line_number, const char *message)

    {

    #ifdef SCPP_THROW_EXCEPTION_ON_BUG

    throw scpp::ScppAssertFailedException(file_name, line_number, message);

    #else

    std::cerr 《 message 《 " in file " 《 file_name 《 " #" 《 line_number 《 std::endl 《 std::flush;

    exit(1);

    #endif // SCPP_THROW_EXCEPTION_ON_BUG

    }

    测试程序:

    [cpp]

    <span style="font-size:18px;">// debug.cpp : 定义控制台应用程序的入口点。

    //

    #include "stdafx.h"

    #include "scpp_assert.h"

    #include "iostream"

    int _tmain(int argc, _TCHAR* argv[])

    {

    std::cout 《 "hello, SCPP_ASSERT" 《 std::endl;

    double stockPrice = 100.0;

    SCPP_ASSERT(0 < stockPrice && stockPrice <= 1.e6,

    "Stock price " 《 stockPrice 《 " is out of range");

    stockPrice = -1.0;

    SCPP_ASSERT(0 < stockPrice && stockPrice <= 1.e6,

    "Stock price " 《 stockPrice 《 " is out of range");

    return 0;

    }</span>

    这个宏可以合成一条有意义的错误,包括与错误有关的更多信息:

    SCPP_ASSERT(0 < stockPrice && stockPrice <= 1.e6,

    "Stock price " 《 stockPrice 《 " is out of range");

    而且在这个宏中,可以使用任何类的对象,只要他定义了《操作符。比如:

    [cpp]

    #include "stdafx.h"

    #include "scpp_assert.h"

    #include "iostream"

    class MyClass

    {

    public:

    bool IsValid(bool flag)

    {

    return flag == true true : false;

    }

    friend std::ostream& operator 《(std::ostream & os, const MyClass &obj);

    };

    inline std::ostream& operator 《(std::ostream & os, const MyClass &obj)

    {

    return os;

    }

    int _tmain(int argc, _TCHAR* argv[])

    {

    std::cout 《 "hello, SCPP_ASSERT" 《 std::endl;

    MyClass obj;

    SCPP_ASSERT(obj.IsValid(false), "this object " 《 obj 《 " is invalid.");

    return 0;

    }

    如果一开始定义了SCPP_THROW_EXCEPTION_ON_BUG那么,即是要打开安全检查,当检查多的时候,速度会有所下降。

      

首页 上一页 2 3 4 5 下一页 尾页 5/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++模板的特化 下一篇调试秘笈-内存泄露原因

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: