编译器能否通过Itself确定变量是否为const? [英] Can the compiler not determine whether a variable is const by Itself?

查看:180
本文介绍了编译器能否通过Itself确定变量是否为const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个函数这个简单的内联函数:

I know for a function this simple it will be inlined:

int foo(int a, int b){
    return a + b;
}

但是我的问题是,编译器不能自动检测是相同的:

But my question is, can't the compiler just auto-detect that this is the same as:

int foo(const int a, const int b){
    return a + b;
}

因为可以检测到,为什么我需要输入 const 在任何地方?我知道 inline 关键字因为编译器的进步而变得过时了。是不是 const 做同样的事情?

And since that could be detected, why would I need to type const anywhere? I know that the inline keyword has become obsolete because of compiler advances. Isn't it time that const do the same?

推荐答案

,编译器可以证明你的例子中的constness。

Yes, the compiler can prove constness in your example.

不,它没有用: - )。

No, it would be of no use :-).

更新: Herb Sutter致力于其中一个主题( http:// www。 gotw.ca/gotw/081.htm )。摘要:

Update: Herb Sutter dedicated one of his gotchas to the topic (http://www.gotw.ca/gotw/081.htm). Summary:


  • const通过使编译器和链接器为包含常量成员函数的const对象选择函数。

  • const不支持通常的翻译单元模型[不同于我的假设]。编译器需要看到整个程序,用于验证事实的常数(这是纯粹的声明不保证),并利用它,以及证明没有混叠...

  • ...和当编译器可以看到整个程序,并且可以证明事实上的constness它实际上当然不再需要const声明了!它可以证明。 Duh。

  • const会产生很大差异的一个地方是定义,因为编译器可能会将对象存储在只读存储器中。

  • const helps most by making the compiler and linker choose functions for const objects including const member functions which can be coded to be more efficient.
  • const doesn't help with the usual translation unit model [differs from what I supposed]; the compiler needs to see the whole program for verifying factual constness (which the mere declaration does not guarantee) and exploiting it, as well as prove the absence of aliasing ...
  • ... and when the compiler can see the whole program and can prove factual constness it actually of course doesn't need the const declaration any longer! It can prove it. Duh.
  • The one place where const makes a big difference is a definition because the compiler may store the object in read-only memory.

这篇文章当然值得阅读。

The article is, of course, worth reading.

翻译通常是必要的利用constness cf.下面的评论从amdn和Angew。

With respect to whole program optimization/translation which usually is necessary to exploit constness cf. the comments below from amdn and Angew.

这篇关于编译器能否通过Itself确定变量是否为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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