与我之前的问题相关:编译器是否不允许假设 const-ref 参数将保持 const 状态? https://stackoverflow.com/questions/49117489/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);
// ...
}
If i
应该在整个函数中保持常量,并且f()
没有副作用,你可以用以下方式声明它__attribute__((pure))
:
int f(const int&) __attribute__((pure));
请注意,这对于 a 来说没有意义pure
返回的函数void
,所以我把它改为int
.
虽然这并不影响如何f()
已编译,它确实会影响调用它的函数(检查它godbolt https://godbolt.org/g/ATxjHB):
#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;
}
}
Here __attribute__((pure))
告诉编译器f()
不会改变i
,因此编译器不会生成对std::cout << ...
.
Without __attribute__((pure))
, 即使f()
被宣布采取const int& i
参数,编译器必须假设的值i
可能会改变,并生成if
并致电std::cout << ...
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)