我知道,出于可读性原因,您应该在通过引用或指针传递参数时尽可能使用 const 关键字。如果我指定一个参数是常量,编译器是否可以做任何优化?
可能有几种情况:
功能参数:
常量引用:
void foo(const SomeClass& obj)
常量 SomeClass 对象:
void foo(const SomeClass* pObj)
还有指向 SomeClass 的常量指针:
void foo(SomeClass* const pObj)
变量声明:
const int i = 1234
函数声明:
const char* foo()
每个都提供什么样的编译器优化(如果有的话)?
最佳答案
案例一:
当你在你的程序中声明一个const
时,
int const x = 2;
编译器可以通过不为这个变量提供存储来优化掉这个const
;相反,它可以添加到符号表中。因此,后续读取只需要间接进入符号表,而不是从内存中获取值的指令。
注意:如果您执行以下操作:
const int x = 1;
const int* y = &x;
那么这将强制编译器为 x
分配空间。因此,对于这种情况,这种程度的优化是不可能的。
对于函数参数而言,const
表示函数中不修改参数。据我所知,使用 const
并没有显着的性能提升;而是一种确保正确性的手段。
案例2:
"Does declaring the parameter and/or the return value as const help the compiler to generate more optimal code?"
const Y& f( const X& x )
{
// ... do something with x and find a Y object ...
return someY;
}
What could the compiler do better? Could it avoid a copy of the parameter or the return value?
不,因为参数已经通过引用传递。
Could it put a copy of x or someY into read-only memory?
不,因为 x
和 someY
都存在于其范围之外,并且来自和/或被给予外部世界。即使 someY
是在 f()
本身内动态分配的,它和它的所有权都交给了调用者。
What about possible optimizations of code that appears inside the body of f()? Because of the const, could the compiler somehow improve the code it generates for the body of f()?
即使调用 const 成员函数,编译器也不能假定对象 x
或对象 someY
的位不会改变。此外,还有其他问题(除非编译器执行全局优化):编译器也可能不确定没有其他代码可能有一个非常量引用,该引用将同一对象与 x
和/或 someY
,以及在执行 f();
期间是否会偶然使用任何此类对同一对象的非 const 引用,编译器甚至可能不知道x
和 someY
只是引用的真实对象,实际上首先声明为 const。
案例 3:
void f( const Z z )
{
// ...
}
Will there be any optimization in this?
是的,因为编译器知道 z
确实是一个 const 对象,即使没有全局分析,它也可以执行一些有用的优化。例如,如果 f()
的主体包含像 g( &z )
这样的调用,编译器可以确定 z
在调用 g()
期间不要更改。
关于c++ - const 在 C/C++ 中提供什么样的优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466642/