首页 > 解决方案 > 何时使用 __declspec(noalias)?

问题描述

据我了解,如果(https://docs.microsoft.com/en-us/cpp/cpp/noalias?view=vs-2019__declspec(noalias)意味着该函数仅修改她体内的内存或通过参数修改,因此它不会修改静态变量或内存通过双指针,对吗?


static int g = 3;

class Test
{
   int x;

  Test& __declspec(noalias) operator +(const int b) //is noalias correct?
  {
    x += b;
    return *this;
  }

  void __declspec(noalias) test2(int& x) { //correct here?
   x = 3;
  }

  void __declspec(noalias) test3(int** x) { //not correct here!?

   *x = 5;
  }
}

标签: c++visual-c++strict-aliasing

解决方案


给定类似的东西:

extern int x;
extern int bar(void);

int foo(void)
{
  if (x)
    bar();
  return x;
}

一个对它一无所知的编译器bar()需要生成允许它可能更改 的值的代码x,因此必须x在函数调用之前和之后加载 的值。虽然一些系统使用所谓的“链接时间优化”来推迟函数的代码生成,直到分析了它调用的任何函数以查看它们可能访问的外部对象(如果有的话),MS 使用了一种更简单的方法,即简单地允许函数原型表示它们不访问调用代码可能想要缓存的任何外部对象。这是一种粗略的方法,但允许编译器以便宜且轻松的方式获得低垂的果实。


推荐阅读