c++ - const 在 C/C++ 中提供什么样的优化?

标签 c++ c constants compiler-optimization

我知道,出于可读性原因,您应该在通过引用或指针传递参数时尽可能使用 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()

每个都提供什么样的编译器优化(如果有的话)?

最佳答案

Source

案例一:

当你在你的程序中声明一个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?

不,因为 xsomeY 都存在于其范围之外,并且来自和/或被给予外部世界。即使 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 引用,编译器甚至可能不知道xsomeY 只是引用的真实对象,实际上首先声明为 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/

相关文章:

c++ - MFC 在标签之间提取 CString

c - 为什么直接给出字符串和读取字符串时strlen返回不同的值?

C:换行十六进制值

c++ - 这个析构函数在 C++ 中有效吗?

c++ - 将类常量存储在数据成员中还是方法中更好?

c++ - 不同模块 (DLL) 的类大小不同。如何以及为什么?

c++ - 从用户定义的函数转到 main()

c++ - 将重叠的应用程序从我的应用程序中移到 x 轴上。多功能 Controller

c++ - 带有内存大小定义的 header

c++ - 将 std::pair<T1, T2> const 转换为 std::pair<T1 const, T2> const 安全吗?