gpt4 book ai didi

c++ - 是否有扩展让优化器假定 const-ref 参数将保持常量?

转载 作者:可可西里 更新时间:2023-11-01 15:23:52 25 4
gpt4 key购买 nike

与我之前的问题相关:Are compilers not allowed to assume const-ref parameters will stay const?

我的新问题是:是否有特定于编译器的非标准扩展或语法来告诉 GCC/Clang/MSVC 对象不可写?例如,这是我希望能够编写的一些伪代码:

void f(const int& i) {

// At this point, compiler doesn't know if "i" can be mutated or not,
// so it assumes it can

// Fake-ish -- compiler now assumes "i" cannot be mutated and optimizes accordingly
__assume(readonly i);

// ...

}

最佳答案

如果i应该在整个函数中保持常量,f()没有副作用,你可以用 __attribute__((pure)) 声明它:

int f(const int&) __attribute__((pure));

请注意,它对于 pure 没有意义函数返回 void , 所以我把它改成了 int .

虽然这不会影响 f()已编译,它确实会影响调用它的函数(在 godbolt 上检查):

#include <iostream>

int f(const int& i) __attribute__((pure));

int main() {
int i = 40;
f(i);
if (i != 40) {
std::cout << "not 40" << std::endl;
}
}

在这里__attribute__((pure))告诉编译器 f()不会改变i , 因此编译器不会生成对 std::cout << ... 的调用.

没有__attribute__((pure)) , 即使f()被宣布采取const int& i参数,编译器必须假定 i 的值可能会改变,并生成 if并调用std::cout << ... .

关于c++ - 是否有扩展让优化器假定 const-ref 参数将保持常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49227571/

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