@property Incorrectly Implemented?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 6 12:37:26 PDT 2016


On Tuesday, September 06, 2016 19:18:11 John via Digitalmars-d wrote:
> Currently it seems that @property isn't implemented correctly.
> For some reason when you try to get the pointer of a property it
> returns a delegate for some reason. This just seems plain wrong,
> the whole purpose of a property is for a function to behave as if
> it weren't a function. There's also some inconsistencies in the
> behavior, "get" is implemented one way and then "set" is
> implemented another.
>
> http://ideone.com/ZgGT2G
>
>      &t.x         // returns "ref int delegate()"
>      &t.x()       // ok returns "int*", but defeats purpose of
> @property
>      &(t.j = 10)  // shouldn't this return "ref int delegate(int)"
> ?
>
> It would be nice to get this behavior fixed, so that it doesn't
> become set in stone. I think returning a delegate pointer is not
> what people would except nor is there really any use case for it.

Okay. How would it work to safely get a pointer to anything but the
@property function when taking its address? &t.x() is just going to give you
the address of the return value - which in most cases, is going to be a
temporary, so if that even compiles in most cases, it's a bit scary. Sure,
if the @property function returns by ref, then it can work, but an @property
function which returns by ref isn't worth much, since you're then giving
direct access to the member variable which is what an @property function is
usually meant to avoid. If you wanted to do that, you could just use a
public member variable.

So, given that most @property functions are not going to return by ref, how
does it make any sense at all for taking the address of an @property
function to do anything different than give you a delegate? Sure, that's not
what happens when you take the address of a variable, but you're not dealing
with a variable. You're dealing with an @property function which is just
trying to emulate a variable.

The reality of the matter is that an @property function is _not_ a variable.
It's just trying to emulate one, and that abstraction falls apart _really_
fast once you try and do much beyond getting and setting the value - e.g.
passing by ref falls flat on its face. We could do better than currently do
(e.g. making += lower to code that uses both the getter and the setter when
the getter doesn't return by ref), but there are some areas where a property
function simply can't act like a variable, because it isn't one. There isn't
even a guarantee that an @property function is backed by memory. It could be
a completely calculated value, in which case, expecting to get an address of
a variable when taking the address of the @property function makes even less
sense.

- Jonathan M Davis



More information about the Digitalmars-d mailing list