Why are properties of concrete types not assignable?

Gregor Richards Richards at codu.org
Mon Nov 27 14:27:49 PST 2006


Sean Kelly wrote:
> I was trying to compose a complex number today and was reminded that 
> this does not work:
> 
>     creal c;
>     c.re = 1.0;
>     c.im = 2.0;
> 
> Why is this?  I can't imagine it's a technical limitation, and I can 
> think of a few instances where this is actually a useful feature 
> (conversion from a string, for example), but there must be some reason 
> for the current behavior.
> 
> The same goes for the array ptr property, though its behavior seems 
> somewhat more understandable:
> 
>     char[] buf;
>     buf.ptr = null; // fails
> 
> I suppose that buf.ptr is just syntactic sugar for &buf[0], and it is 
> not assignable so the length property is always accurate?  And the .len 
> struct member is not exposed to avoid confusing with .length?  This 
> seems reasonable, though I've encountered a few instances where I wanted 
> to manually manipulate these properties to avoid the risk of 
> reallocation and wished they were assignable.  But slicing is powerful 
> enough that direct member manipulation really isn't necessary, so 
> perhaps it's safer to keep things the way they are for arrays.
> 
> 
> Sean

I agree that .re and .im should probably be assignable. It's virtually 
impossible to break something like that, and I think that realistically 
you'll always get the value you want.

However, I don't agree that properties of dynamic arrays should be 
assignable. In my opinion, if you want to hack around at them, you 
should have to actually hack around at them:

union charray {
     char[] darr;
     struct {
         void *ptr;
         int len;
     }
}


That was at least it's very clear that you're doing something nasty, not 
something you could "accidentally" fall into.

Just my 2¢

  - Gregor Richards



More information about the Digitalmars-d mailing list