C++ 核心准则边译边学 哲学篇.5: Prefer compile-time checking to run-time checking 尽可能编译器检查而不是运行期检查

源网址:CppCoreGuidelines

原因

代码清晰和高效。你不需要对编译期捕获的错误写异常处理。

例子

// Int is an alias used for integers
int bits = 0;         // don't: avoidable code
for (Int i = 1; i; i <<= 1)
    ++bits;
if (bits < 32)
    cerr << "Int too small\n";

这个例子不能实现它想要的功能(因为溢出未定义),可以替换为简单的static_assert

// Int is an alias used for integers
static_assert(sizeof(Int) >= 4);    // do: compile-time check

或者最好用类型系统把Int替换为int32_t

例子

void read(int* p, int n);   // read max n integers into *p

int a[100];
read(a, 1000);    // bad, off the end

更好的写法:

void read(span<int> r); // read into the range of integers r

int a[100];
read(a);        // better: let the compiler figure out the number of elements

替换原理

在编译期能做好的事情不要推迟到运行期

补充

  • 寻找指针参数。
  • 查找范围违规的运行时检查。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值