Alternative solutions to returning ref types.

Bill Baxter dnewsgroup at billbaxter.com
Sat Mar 15 03:44:40 PDT 2008


kede wrote:
> Hi...
> 
> I'm still having a great time using D for graphics programming at the moment.
> However, I'm constantly irritated by my initial design decision to implement the lower level objects as structs simply because it has led do (a now ridiculous amount) of code along the lines of the following:
> 
> model.origin = model.origin + vec3(0,1,0);
>  -- or --
> o = model.origin;
> o.y += 1;
> model.orgin = o;

I take it model.origin is a get/set property method pair?  If in C++ you 
would be willing to make it a reference-returning method then you might 
just want to make it a regular data member.  Returning references 
basically means giving up most of your encapsulation benefit in the 
first place.  And since methods and members can be accessed with the 
same syntax in D you can just change it back to property methods later 
if the need for encapsulation arises.

> When all I really want is just:   model.origin.y++;
> Worse still, model.origin.y++ is legal but doesn't do what you would expect.

You can define a static data member vec3.UnitY.  Then if origin is a 
plain data member then this works:
    model.origin += vec3.UnitY;

> 
> I'm sure most of you have this problem to some degree or another.  However, it doesn't look like returnable ref types are going to be implemented in D any time soon, so I want to ask you guys what you are currently doing to deal with this.

It is annoying, yes.

> For the sake of discussion take a 3d vector object as an example.
> Given that it is small in size, frequently allocated and deallocated, commonly used inside other class objects.
> 
> The obvious solutions are:
> 1. Use a pointer to return it.  -- urgh

I often end up having a regular .thing() method for typical uses, and in 
addition a .thing_ptr() method that returns a pointer for the cases 
where you really need to get an lvalue.

> 2. Implement it as a class.
> 3. As 2 with custom 'new' 'delete'
> 
> 
> Thanks in advance for any ideas you might have...

It is definitely annoying.  The idea of gating all reads and writes 
through property methods is nice, but if that's how D wants us to do it, 
then the compiler really should rewrite expressions like a.foo += bar 
for us (as a.foo = a.foo+bar).  This has been suggested several times in 
the past.  And apparently some other languages do just that (I think C# 
was the one brought up).

I guess it just isn't a priority with Walter.  It's a shame because it 
seems like it would be pretty easy to put those rewrite rules into 
place.  But maybe its harder than I'm thinking.

--bb



More information about the Digitalmars-d mailing list