问题
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?"
Qualifying
this
(restrict a method):void Foo::method(int*__restrict a) __restrict { /*...*/ }
Restrict a reference:
int&__restrict x = /*...*/;
Restrict inside a template:
std::vector<float*__restrict> x;
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:
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 aliasother
.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.
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.
There is precedent on this question. In short, in function
f
, the compiler knows thata.field
andb.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 therestrict
keyword is unnecessary (and impossible) to apply.
来源:https://stackoverflow.com/questions/25940978/c-restrict-semantics