C++_知识点——断言

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;
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值