If a function parameter is annotated const int &x
and I try to do x++
in the function body, I get a compile time error for modifying a read-only reference. But if I use the __restrict__
modifier like so:
void foo(int & __restrict__ a, int & __restrict__ b) {
if (a == 1)
b = 2;
if (a == 2)
b = 3;
}
int main() {
int x = 1;
foo(x, x); // should be illegal?
cout << x;
}
...I do not get a compile time error. If I run this code unoptimized the output is 3
, but if I run it with -O1
or higher the output is 2
. It seems like detecting x
to be passed twice would be straightforward and easy to disallow. Why does C++ protect against bad use of const
but not bad use of __restrict__
?