C++ restrict Semantics

不羁岁月 提交于 2019-12-05 08:34:49
imallett
  1. Qualifying this (restrict a method):

    This means that the this pointer is restricted. This one major consequence:

    • The method can't operate on itself as data, e.g.:

      void Foo::method(Foo*__restrict other) __restrict { /*...*/ }
      

      In that example, this might otherwise alias other. restrict is saying that you can't call this method with itself as an argument.

    • Note: it is okay to access or change the object, even through a field. The reason why is that the following are functionally identical:

      void Foo::method1(void) __restrict { field=6; }
      void Foo::method2(void) __restrict { this->field=6; }
      

      In that example, this is not aliased with anything.

  2. Restrict a reference:

    It appears to mean exactly that--that the reference is restricted. What this exactly does and whether it's useful is another matter. Someone on this thread claims compilers can statically determine aliasing for references, and so the keyword is supposedly useless. This question was also asked about whether it should be used, but the answer "vendor specific" is hardly helpful.

  3. There is precedent on this question. In short, in function f, the compiler knows that a.field and b.field are not aliased:

    class Foo final {
        int*__restrict field;
    };
    int f(Foo a, Foo b) { /*...*/ }
    

    This will often be the case, assuming a!=b--for example, if field is allocated and destroyed by the constructor/destructor of Foo. Note that if field is a raw array, it will always be true and so the restrict keyword is unnecessary (and impossible) to apply.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!