C ++中的常量和编译器优化 [英] Constants and compiler optimization in C++

查看:152
本文介绍了C ++中的常量和编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于C ++中的const正确性的所有建议,这是重要的(部分),因为它有助于编译器优化你的代码。我从来没有见过的是一个很好的解释,编译器如何使用这些信息来优化代码,甚至没有好的书去解释幕后发生了什么。

I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, not even the good books go on explaining what happens behind the curtains.

例如,编译器如何优化一个被声明为const的方法,而不是一个不是但应该是的方法。当引入可变变量时会发生什么?它们会影响const方法的这些优化吗?

For example, how does the compiler optimize a method that is declared const vs one that isn't but should be. What happens when you introduce mutable variables? Do they affect these optimizations of const methods?

推荐答案

让我们忽略方法,编译器在这里有更多的优化机会。如果对象被声明为const,那么(ISO / IEC 14882:2003 7.1.5.1(4)):

Let's disregard methods and look only at const objects; the compiler has much more opportunity for optimization here. If an object is declared const, then (ISO/IEC 14882:2003 7.1.5.1(4)):


声明
mutable(7.1.1)可以被修改,任何
尝试修改一个const对象
在其生命周期(3.8)导致
未定义的行为。

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

允许忽略可能有可变成员的对象 - 编译器可以自由地假定对象不会被修改,因此它可以产生显着的优化。这些优化可以包括以下内容:

Lets disregard objects that may have mutable members - the compiler is free to assume that the object will not be modified, therefore it can produce significant optimizations. These optimizations can include things like:


  • 将对象的值直接合并到机器指令操作码

  • 完全删除因为const对象在编译时已知的条件表达式中使用而永远无法访问的代码

  • 循环展开,如果const对象正在控制迭代的次数循环

请注意,只有当实际的对象是const时,这个东西才适用 - 不适用于通过const指针访问的对象,引用,因为这些访问路径可能导致不是const的对象(通过const指针/引用来更改对象,只要实际的对象是非const的,并且你抛弃了对象的访问路径的constness) )。

Note that this stuff applies only if the actual object is const - it does not apply to objects that are accessed through const pointers or references because those access paths can lead to objects that are not const (it's even well-defined to change objects though const pointers/references as long as the actual object is non-const and you cast away the constness of the access path to the object).

在实践中,我不认为有编译器对所有类型的const对象执行任何重要的优化。但对于是原始类型(int,chars等)的对象我认为编译器可以相当积极地优化
使用这些项目。

In practice, I don't think there are compilers out there that perform any significant optimizations for all kinds of const objects. but for objects that are primitive types (ints, chars, etc.) I think that compilers can be quite aggressive in optimizing the use of those items.

这篇关于C ++中的常量和编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆