Give struct the status it deserves
Hong
Hong_member at pathlink.com
Sat Mar 25 01:48:45 PST 2006
Structs are second class citizens of... or maybe refugees of D, they are victims
of discrimination.
Following are the reasons:
1. most D programmers don't use struct, unless they happen to be the poor guy
writing the C interface.
2. to use structs you have to use pointers, but the spec says pointers are only
provided for C compatibility, structs are to be avoided as long as the world
spins.
3. pointers + overloaded operators make a mess.... this is a less offensive
example: (*o) = (*t)[(*i) * (*j)] ... the pointers and operators are abusing
each other.
4. structs cannot have constructor, "static opCall" is best you can do.
5. structs are more efficient? Not when structs are passed around by value. To
change a struct member: 1. make a copy 2. change the copy 3. Copy the copy back
into the original location. Two damned copies for.... efficiency.
6. yes, you can use pointers to change a struct member without copying, if you
can be bothered to define 2 accessor methods, one returns a copy another one
returns a pointer.
7. Most standard containers (DTL) do not allow a pointer to a contained struct
to be retrieved, all changes, or just about anything has to be done via copies.
8. structs have different behaviours between array and Vector, array [] returns
a reference, Vector [] returns a copy, nice rookie trap.
Imho, following are little suggestions for structs to make first class citizens
of D:
1. have some sort of reference semantic to replace pointers. Pointers are not
necessary unless structs are used with "new"
2. add constructor for struct, destructors are not necessary.
I use structs because I need efficiency and stack allocated data structures,
however, it is painful to see a C++ program turns into a C like program when
ported to D.
More information about the Digitalmars-d
mailing list