C `restrict` keyword in D
Uknown via Digitalmars-d
digitalmars-d at puremagic.com
Sat Sep 2 20:04:58 PDT 2017
In C, the `restrict` keyword implies that 2 or more pointer
arguments in a function call do not point to the same data. This
allows for some additional optimizations which were not possible
before, finally making C as fast as Fortran.
This is the new definition for memcpy in C99
void* memcpy(void *restrict dst, const void *restrict src, size_t
`dst` and `src` should never point to the same block of memory,
and this is enforced by the programmer.
In D, it makes sense to add a similar functionality, that extends
beyond just performance optimizations. It could potentially be
used to better guarantee @safety of some code.
e.g. (from discussions about ref counting in D) :
void main() @safe
auto arr = RCArray!int();
void foo(ref RCArray!int arr, ref int val) @safe
auto copy = arr; //arr's (and copy's) reference counts are both 2
arr = RCArray!int(); // There is another owner, so arr
// forgets about the old payload
} // Last owner of the array ('copy') gets destroyed and
// frees the payload.
val = 3; // Oops.
Here, adding `restrict` to foo's parameters like so :
void foo(restrict ref RCArray!int arr, restrict ref int val)
would make the compiler statically enforce the fact that neither
references are pointing to the same data. This would cause an
error in main, since arr is from the same block of memory as
The same would apply for pointers.
I just hope to have a nice discussion on this topic here.
Read more about `restrict` here :
More information about the Digitalmars-d