BOOST_ASSERT在debug模式下有效。
#include <iostream> #include <boost/assert.hpp> using namespace std; using namespace boost; double fun(int x) { BOOST_ASSERT(x!=0 && "divede by zero"); return 1.0/x; } int main() { fun(0); return 0; }
获取更多的诊断信息:
#include <iostream> #include <boost/assert.hpp> #include <boost/format.hpp> using namespace std; using namespace boost; #define BOOST_ENABLE_ASSERT_HANDLER namespace boost { void assertion_failed(char const * exptr,char const *function,char const * file,long line) { boost::format fmt("Assertion failed! Expression: %s Function :%s File %s Line:%ld "); fmt % exptr % function % file%line; cout << fmt; } } double fun(int x) { BOOST_ASSERT(x!=0 && "divede by zero"); return 1.0/x; } int main() { fun(0); return 0; }
静态断言,将错误转移到编译期内
#include <iostream> #include <boost/static_assert.hpp> using namespace std; using namespace boost; template<typename T> T my_min(T a,T b) { BOOST_STATIC_ASSERT(sizeof(T) < sizeof(int)); return a < b ? a:b; } int main() { cout << my_min((short)1,(short)3); //cout << my_min(1L,3L); return 0; }