问题描述
在方法中,通常 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++:
(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)生成更快的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!