Give struct the status it deserves

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Mar 27 08:35:23 PST 2006


Stewart Gordon wrote:
> Hong wrote:
>> Structs are second class citizens of... or maybe refugees of D, they 
>> are victims
>> of discrimination.
>> Following are the reasons:

[snip]

>> 4. structs cannot have constructor, "static opCall" is best you can do.
> 
> What's wrong with that?  Do you simply miss the word "new" in uses of 
> static opCall?

The problem with not having real constructors is that you can not 
guarantee that your struct gets initialized correctly.

>> 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.
> 
> If you want classes, you know where to find them.

Small structs (the cases were structs are most useful) can often more 
efficient to pass by value than by reference.

>> 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.
> 
> Why would anyone want to do that?  What's wrong with simply
> 
>     Qwert yuiop = asdfg;    // to create a copy
>     Qwert* zxcvb = &asdfg;  // to create a pointer

If I understand correctly, Hong is talking about struct members (i.e. a 
member variable of a struct type), that should be accessed through an 
accessor method. I.e:

Array!(Position) points = ...;
points[5].x = 7;

Or:

myInstance.pos.x = 5;
(Where pos is accessed through a getter method)


>> 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.
> 
> That's an issue with those containers, rather than with structs themselves.

I agree that this is not an issue with structs.  But it is an issue with 
the language. Given:

struct Position { int x,y; }

There is no way to duplicate the behavior of:

Position[] points = ...;
points[5].y = 5;
points[3].x += 2;

With an user defined container type.

>> 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"
> 
> Maybe you could elaborate on how these reference semantics would work 
> such that they'd be any different from classes.

You could consider:

struct MyPointContainer {
	Position[] points;
	inout Position opIndex(uint ix) { return &points[ix]; }
}

Where inout denotes that the struct is returned by reference.

/Oskar



More information about the Digitalmars-d mailing list