Are there extensions to let optimizers assume const-ref parameters will stay const?

前端 未结 2 1233
旧巷少年郎
旧巷少年郎 2021-02-14 03:58

Related to my former question: Are compilers not allowed to assume const-ref parameters will stay const?

My new question is: Is there compiler-specific, non-standard ext

2条回答
  •  没有蜡笔的小新
    2021-02-14 04:42

    If i is supposed to stay const for the whole function, and f() has no side effects, you could declare it with __attribute__((pure)):

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

    Note that it doesn't make sense for a pure function to return void, so I changed it to int.

    While this does not affect how f() is compiled, it does affect the functions calling it (check it on godbolt):

    #include 
    
    int f(const int& i) __attribute__((pure));
    
    int main() {
        int i = 40;
        f(i);
        if (i != 40) {
            std::cout << "not 40" << std::endl;
        }
    }
    

    Here __attribute__((pure)) tells the compiler that f() will not change i, so the compiler will not generate the call to std::cout << ....

    Without __attribute__((pure)), even if f() is declared to take a const int& i parameter, the compiler has to assume that the value of i may change, and generate the if and the call to std::cout << ... .

提交回复
热议问题