温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++编译时为什么检查比执行时检查更好

发布时间:2021-11-24 16:39:14 来源:亿速云 阅读:90 作者:iii 栏目:大数据

这篇文章主要讲解了“C++编译时为什么检查比执行时检查更好”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++编译时为什么检查比执行时检查更好”吧!

P.5: Prefer compile-time checking to run-time checking(编译时检查比执行时检查更好)

Reason(原因)

Code clarity and performance. You don't need to write error handlers for errors caught at compile time.

代码的清晰和性能。你不需要为编译错误编写处理程序。

译者注:编译时检查不会占用执行时间,因此可以带来更好的性能;编译检查一般都是利用编译器,语言的基本功能,检查代码也会清晰明了。

Example(示例)

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

This example fails to achieve what it is trying to achieve (because overflow is undefined) and should be replaced with a simple static_assert:

这个例子无法达成它想要达成的目标(因为溢出时的行为是无定义的)。它可以被一个简单的static_assert代替:

译者注:

  1. 代码应该是想通过一个循环的左移操作计算Int的位数,如果小于32位就报错。这是一种运行时检查的方式。

  2. static_assert支持编译时的断言检查。

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

Or better still just use the type system and replace Int with int32_t.

或者直接使用类型系统并且用intr32_t代替Int。

Example(示例)

void read(int* p, int n);   // read max n integers into *p
int a[100];read(a, 1000);    // bad, off the end

better(好一点)

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

译者注:使用指针传递数据的read可以使用int型的大小信息进行范围检查但是这种检查只能在执行时进行;而span包含了数组的尺寸信息,如果数组长度在编译时可以确定,span就可以实现编译时的范围检查。

Alternative formulation: Don't postpone to run time what can be done well at compile time.

另一个表达:编译时能做的,就不要延迟到执行时。

Enforcement(执行建议)

  • Look for pointer arguments.注意指针类型参数。

  • Look for run-time checks for range violations.注意运行时刻对范围违反的检查。

译者注:通过指针传递数据之后,大小信息也作为变量传递,因此之后的范围检查都只能在执行时进行。有了模板类span之后,这些检查都可以重新考虑,看看是否可以转变成编译时检查。

感谢各位的阅读,以上就是“C++编译时为什么检查比执行时检查更好”的内容了,经过本文的学习后,相信大家对C++编译时为什么检查比执行时检查更好这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI