整数到指针投射悲观优化机会

Dan*_*non 0 c++ clang clang-tidy

from_base函数将内存地址从基址返回到程序中选定的值。我想检索该值并将其返回到函数中,但是,我收到一条警告,提示integer to pointer cast pessimism optimization opportunities.

DWORD chat::client() {
    return *reinterpret_cast<DWORD*>(core::from_base(offsets::chat::client));
}
Run Code Online (Sandbox Code Playgroud)

从程序中转换函数时我也收到此警告:

auto og_print = reinterpret_cast<chat::fn_print_chat>(core::from_base(offsets::chat::print));
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我会收到 clang-tidy 的警告integer to pointer cast pessimism optimization opportunities

性能无int-to-ptr

我查了一下,但我无法弄清楚。该代码有效,并获得正确的值。我只是担心这个警告。

sup*_*cat 5

如果程序执行如下计算:

char x[10],y[10];
int test(ptrdiff_t i)
{
  int *p = x+i;
  *p = 1;
  y[1] = 2;
  return *p;
}
Run Code Online (Sandbox Code Playgroud)

编译器有理由认为,因为p是通过指针算术使用 形成的x,所以它不可能 equal y+1,因此该函数将始终返回 1。但是,如果代码编写为:

char x[10],y[10];
int test(ptrdiff_t i)
{
  int *p = (char*)((uintptr_t)x + i);
  *p = 1;
  y[1] = 2;
  return *p;
}
Run Code Online (Sandbox Code Playgroud)

那么这样的假设就不太合理,因为无符号数字语义将定义 的行为uintptr_t z = (uintptr_t)(y+1)-(uintptr_t)x产生一个等于 的x+z(uintptr_t)(y+1)

我发现 clang 在这里表现出的明显警告有点令人惊讶,因为 clang 很容易假设,给定一些指针char*p,不可能if to equalp而for to equal 。标准并不禁止这样的假设,但话又说回来,它也不会禁止这样的假设:代码永远不会将任何整数到指针转换的结果用于除与其他指针比较之外的任何目的。支持类型的实现当然应该为往返指针提供更强的保证,而不仅仅是说它们可以与原始指针进行比较,但标准并不要求这样的处理。y(uintptr_t)p(uintptr_t)(x+10)pyuintptr_t