gpt4 book ai didi

c++ - 优化器 : replace const reference with const object

转载 作者:IT老高 更新时间:2023-10-28 22:26:31 25 4
gpt4 key购买 nike

Chandler Carruth 在他的 talk关于编译器优化 说编译器在优化具有通过引用传递的参数的函数方面很糟糕。我可以理解当参数是非常量引用时很困难,因为编译器必须处理内存,或者当参数的类型很复杂(一些奇怪的结构或类)时。但是如果参数是 const 引用和内置类型,真的有什么问题吗?优化器可以用 const float 替换 const float& 吗?当启用 SSE 指令时,它会更有帮助,因为编译器将能够为它们正确对齐数据。

最佳答案

Can optimizer replace const float& with const float?

不,他们不能这样做,因为它可能会改变程序的语义。一个 const引用仍然是引用。它不能被值(value)取代。考虑这个例子:

void foo(const float& x, float a[]) {
cout << x << endl;
a[0] += 10.5;
cout << x << endl;
}

int main() {
float a[1] = { 3.25 };
foo(a[0], a);
return 0;
}

打印出来

3.25
13.75

Demo 1

如果您更改 const float&const float ,结果是

3.25
3.25

Demo 2

这里的问题是 a[0]x 相同,但连接是由调用者建立的,不在优化器的控制范围内。

关于c++ - 优化器 : replace const reference with const object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com