C++ restrict Semantics

走远了吗. 提交于 2020-01-02 04:50:22

问题


I'm in the process of updating performance critical libraries to use restrict, as implemented in C++11 by g++ and MSVC with the keyword __restrict. This seems to be the most-standard-extension, so I'll use restrict and __restrict interchangeably.

restrict is a C99 keyword, but nevertheless compilers have defined important uses for it in C++.

This post intends to be a "question" asking about what each C++-specific use is and what it means, followed by a CW answer answering it. Feel free to add/check/edit. So: "Help! What do these C++ uses of the restrict keyword mean?"

  1. Qualifying this (restrict a method):

    void Foo::method(int*__restrict a) __restrict { /*...*/ }
    
  2. Restrict a reference:

    int&__restrict x = /*...*/;
    
  3. Restrict inside a template:

    std::vector<float*__restrict> x;
    
  4. Restrict a member/field. This technically also applies to C's struct, but it comes up as an issue in C++ more often than it does in C:

    class Foo final { public: int*__restrict field; };
    

回答1:


  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.



来源:https://stackoverflow.com/questions/25940978/c-restrict-semantics

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