做“const”声明有助于编译器(GCC)生成更快的代码? [英] do "const" declarations help the compiler (GCC) produce faster code?

查看:229
本文介绍了做“const”声明有助于编译器(GCC)生成更快的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const 声明可以帮助编译器(GCC)生成更快的代码,还是仅用于可读性和正确性?

Zed Shaw认为 const 在C / C ++中是无用的或被滥用的:



接下来是所有对const的奇怪魅力。由于某些奇怪的原因,
C ++喜欢让你在声明的每一部分使用const,并且
但是我得到了和C一样的最终结果:一个函数被调用。 (...)


(From:http://librelist.com/browser//mongrel2/2010/7/15/c-verses-c++/#770d94bcfc6ddf1d8510199996b607dd

解决方案

在方法中,通常 const 修饰符无法使用引用和指针出于几个原因来优化代码。最主要的是 const 修饰符在这些上下文中不会保证底层数据不会发生变化,它只是使修改它变得更加困难。这是一个典型的例子

  void M(const C& p1,C& p2){
cout<< ; p1.field<< ENDL;
p2.Mutate();
cout<< p1.field<< ENDL;

$ / code>

在这种情况下, p1.field在此代码中修改。最明显的例子是 p1 p2 引用相同的值。

  C本地; 
M(本地,本地);

因此,编译器在这里没有真正的优化。 const 参数与非const类型一样危险。



另一个原因是它不能真正优化的是任何人都可以用C ++作弊, const_cast

  class C {
public:
int field;

int GetField()const {
C * pEvil = const_cast< C *>(this);
pEvil-> field ++;
返回字段;
}
};

所以,即使你正在处理一个 const 引用的值仍然可以在引擎盖下自由更改。

Do const declarations help the compiler (GCC) produce faster code or are they only useful for readability and correctness?

Zed Shaw has argued that const is useless or is overused in C/C++:

Next is all the bizarre fascination with const. For some odd reason C++ loves to make you slap const on every part of a declaration, and yet I get the same end result as C: a function is called. (...)

(From: http://librelist.com/browser//mongrel2/2010/7/15/c-verses-c++/#770d94bcfc6ddf1d8510199996b607dd )

解决方案

In general const modifier on method, references and pointers can't be used to optimize code for a couple of reasons. The primary one is that const modifier, in those contexts, doesn't make any guarantees about the underlying data not changing, it just makes it harder to modify it. Here is a classic example

void M(const C& p1, C& p2) { 
  cout << p1.field << endl;
  p2.Mutate();
  cout << p1.field<< endl;
}

In this case it's very possible that p1.field is modified in this code. The most obvious case is that p1 and p2 refer to the same value.

C local;
M(local, local);

Hence there is no real optimization the compiler can do here. The const parameter is equally as dangerous as the non-const one.

The other reason why it can't really optimize is that anyone can cheat in C++ with const_cast.

class C { 
public:
  int field;

  int GetField() const { 
    C* pEvil = const_cast<C*>(this);
    pEvil->field++;
    return field;
  }
};

So even if you are dealing with a single const reference the values are still free to change under the hood.

这篇关于做“const”声明有助于编译器(GCC)生成更快的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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