gpt4 book ai didi

c++ - GCC `__attribute__ ((pure))` 关于 "input state"getter 方法的建议 - 正确吗?

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:55 27 4
gpt4 key购买 nike

使用 -Wsuggest-attribute=pure 编译使 GCC 建议可以用 __attribute__ ((pure)) 标记的潜在函数以进行优化。

这是 definition of pure关于 GCC 的文档:

Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure.

我正在创建一个小型游戏引擎,其中有一个包含 input_state 成员的 input_context 类。 input_context 类通过从操作系统获取全局输入状态来更新每一帧的 input_state 成员。

它还包含几个“getter”来查询输入状态。

简化示例:

class input_context
{
private:
input_state _input_state;

public:
void update()
{
os::fill_input_state(_input_state);
}

auto mouse_x() const noexcept
{
return _input_state._mouse_x;
}

auto mouse_y() const noexcept
{
return _input_state._mouse_y;
}

auto is_key_down(keycode k) const noexcept
{
// `_keys` is an array of `bool` values.
return _input_state._keys[k];
}
};

GCC 告诉我所有这些“getter 方法”,例如 mouse_x()mouse_y()is_key_down(),都是__attribute__ ((pure)) 的候选人。

我应该将这些方法标记为吗?

我不这么认为,但是 GCC 的建议让我想知道。

我不确定如何解释 GCC 对 pure 的定义 - 它说那些只依赖于参数和/或全局变量的函数应该被标记为这样.

  • 在某种程度上,全局操作系统输入状态可以解释为全局变量

  • 另一方面,“getter 方法”总是返回不同的值,具体取决于 _input_state 成员变量。

最佳答案

我认为将其标记为纯净是可以的。以简化形式考虑您的示例,并添加了一些 IO 功能:

#include <stdio.h>
class X {
int x_=0;
public:
int x() const noexcept __attribute__ ((pure)) /*__attribute__((noinline))*/;
void inc() noxcept { x_++; }
};
int X::x() const noexcept { puts("getting x"); return x_;}
int main(){
X x;
printf("%d\n", x.x() + x.x() + x.x());
x.inc();
printf("%d\n", x.x() + x.x() + x.x());
}

pure 让您获得:

getting x
0
getting x
3

代替

getting x
getting x
getting x
0
getting x
getting x
getting x
3

在优化级别至少 -O1(在更高级别,您可能需要添加 __attribute__((noinline)) 以防止内联)。

如果在对这些 getter 的两次连续调用之间状态发生变化,只要编译器可以检测到状态已发生变化,那也没关系。如果您需要运行 非常量 方法来更改状态,那么这不违反纯度。然而,如果状态以编译器无法获知的方式改变自己(系统改变它/另一个线程改变它/信号处理程序改变它),那么pure 属性不再合法。

关于c++ - GCC `__attribute__ ((pure))` 关于 "input state"getter 方法的建议 - 正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136673/

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