static_assert:
我们可以在编译期间发现更多的错误,用编译器来强制保证一些契约,并帮助我们改善编译信息的可读性,尤其是用于模板的时候。
static_assert的第一个参数是常量表达式,可以用在全局作用域中,命名空间中,类作用域中,函数作用域中,几乎可以不受限制的使用。编译器在遇到一个static_assert语句时,通常立刻将其第一个参数作为常量表达式进行演算,但如果该常量表达式依赖于某些模板参数,则延迟到模板实例化时再进行演算,这就让检查模板参数成为了可能。
由于是static_assert编译期间断言,不生成目标代码,因此static_assert不会造成任何运行期性能损失。
struct A { };
struct B { B(B&&) {} };
struct C { C(C&&) noexcept {} };
int main()
{
static_assert(std::is_nothrow_move_constructible<A>::value,
"class A requires noexcept move-constructible type");
static_assert(std::is_nothrow_move_constructible<B>::value,
"class B requires noexcept move-constructible type");
static_assert(std::is_nothrow_move_constructible<C>::value,
"class C requires noexcept move-constructible type");
}
assert:
assert的表达式既可以是常量,也可以是变量,它处于运行期间检测
#include <assert.h>
using namespace std;
int main()
{
int a = 10, b = 2;
//使用断言,若assert()中为false,则程序终止退出
assert(a < b);
cout << a << b << endl;
}