Alias this does not work with pointers?
Chris Wright via Digitalmars-d
digitalmars-d at puremagic.com
Wed Mar 9 20:53:19 PST 2016
alias this can do so much more, though.
For instance:
struct Foo {
int a;
string b;
alias a this;
}
void bar(int* p, size_t len) {
for (int i = 0; i < len; i++) {
p[i] = 0;
}
}
bar(new Foo[2].ptr, 2);
Two fields. You don't want to overwrite a pointer, so you can't just turn
it to an implicit cast.
Or another example:
struct Foo {
double s;
int square() { return cast(int)(s * s); }
alias square this;
}
How do you convert a Foo* to an int*? Do you allocate space for it on the
heap? But what if the Foo* points to a malloc'd section of memory? Or
some other allocator? Or if it's on the heap and the function is marked
@nogc? You could put it on the stack as an alternative, but then the
pointer will be invalid when the function exits... What if it's sent off
to a C function that stores it? Should the allocation be pinned by
default? When would it be unpinned?
It's a silent, hidden allocation beyond the user's control. We would like
it to be allocated like the Foo* was allocated, but that's not currently
possible.
Instead of providing an implementation that occasionally works but
typically causes a crash or an unavoidable inefficiency, it's just not
there to trip people up.
More information about the Digitalmars-d
mailing list