在 C++ 中实现断言检查的最佳方法是什么?

问题描述:

我的意思是,我需要做什么才能在我的代码中使用有用的断言?

By that I mean, what do I need to do to have useful assertions in my code?

MFC 很简单,我只用 ASSERT(something).

MFC is quite easy, i just use ASSERT(something).

什么是非 MFC 方式?

What's the non-MFC way?

是否可以在 assert.c 而不是我的文件中停止断言中断,而不是我调用 assert() 的文件?

Is it possible to stop assert breaking in assert.c rather than than my file which called assert()?

& 之间有什么区别??

What's the difference between <assert.h> & <cassert>?

接受的答案:这篇文章中有很多很棒的答案,我希望我能接受不止一个答案(或者有人将它们全部结合起来).所以答案被授予 Ferruccio(第一个答案).

Accepted Answer: Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).

#include <cassert>

assert(something);

对于编译时检查,Boost 的静态断言非常有用:

and for compile-time checking, Boost's static asserts are pretty useful:

#include <boost/static_assert.hpp>

BOOST_STATIC_ASSERT(sizeof(int) == 4);  // compile fails if ints aren't 32-bit