Finding out about D - 102
Steve Teale
steve.teale at britseyeview.com
Mon May 11 10:48:33 PDT 2009
OK, so structs are a different beast in D than they are in C++. This results in one of my most common pitfalls. I'll find myself writing:
struct A
{
int a;
int b;
}
A[] nameTooLong = ...;
foreach (whatever; thingie)
{
nameTooLong[whatever.whatever].a = whatever.x*3;
nameTooLong[whatever.whatever].b = whatever.y/3;
// more of the same sort of stuff
}
So I get fed up typing 'nameTooLong[whatever.whatever]', and instead I write
foreach (whatever; thingie)
{
A ntl = nameTooLong[whatever.whatever];
ntl.a = whatever.x*3;
ntl.b = whatever.y/3;
// more of the same sort of stuff
}
Then I chase a bug in my program, which compiled OK. After some time, I realize that
A ntl = nameTooLong[whatever.whatever];
is doing a copy, which is not what I was thinking about at all - old C++ habits.
ntl = ...;
has no effect whatsoever on nameTooLong[whatever.whatever].
So then - pissed off by that point - I rewrite it as:
foreach (whatever; thingie)
{
A* ntl = &nameTooLong[whatever.whatever];
// This suggests an ambiguity in the language?
ntl.a = whatever.x*3;
ntl.b = whatever.y/3;
// more of the same sort of stuff
}
This works OK, but it's still not the D way to do things. Try:
foreach (whatever; thingie)
{
alias nameTooLong[whatever.whatever] ntl;
ntl.a = whatever.x*3;
ntl.b = whatever.y/3;
// more of yer same sort of stuff
}
More information about the Digitalmars-d-learn
mailing list