是否有扩展让优化器假设const-ref参数将保持const?

Jef*_*f M 11 c++

与我之前的问题相关:编译器是否不允许假设const-ref参数将保持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);

    // ...

}
Run Code Online (Sandbox Code Playgroud)

fwy*_*ard 5

如果i整个函数应该保持常量,并且f()没有副作用,您可以使用以下方式声明它__attribute__((pure)):

int f(const int&) __attribute__((pure));
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里__attribute__((pure))告诉编译器f()不会改变i,所以编译器不会生成对std::cout << ....

如果没有__attribute__((pure)),即使f()声明为带const int& i参数,编译器也必须假设 的值i可能会改变,并生成if和对 的调用std::cout << ...。