shu*_*e87 10 c++ portability gcc
我正在编写一些代码,其中有许多简单的纯函数可以被调用很多.如果这些函数得到优化以便不经常调用,那么这是非常安全的.
目前我使用gcc作为我的编译器,我想知道是否有一种可移植的方式:
int foo(int) __attribute__ ((pure))
Run Code Online (Sandbox Code Playgroud)
有关纯关键字的信息可以在这里找到:http: //www.ohse.de/uwe/articles/gcc-attributes.html#func-pure
如果pure关键字不可用,我将如何实现类似的东西呢?
从 C++11 开始,您可以使用带有 GCC 特定属性的标准化属性语法:
[[gnu::pure]]
int foo(int)
Run Code Online (Sandbox Code Playgroud)
从 C++17 开始,这保证在任何编译器上都没有问题,因为如果他们不识别[[gnu::pure]],他们必须无误地忽略它。
#ifdef __GNUC__
#define __pure __attribute__((pure))
#else
#define __pure
#endif
Run Code Online (Sandbox Code Playgroud)
__pure需要时使用