Properties: a.b.c = 3

Steven Schveighoffer schveiguy at yahoo.com
Wed Jul 29 09:50:06 PDT 2009


On Tue, 28 Jul 2009 22:33:53 -0400, Walter Bright  
<newshound1 at digitalmars.com> wrote:

> The issue is what if b is a property, returns a temporary object, and  
> that temp's .c field is uselessly set to 3?

There's one way you could do it -- since the return value is a temporary,  
it should not be an lvalue.  But it's members could be lvalues, but only  
if they 1) are reference types or 2) implement opAssign.

So for instance:

struct S1
{
   int c;
}

If a.b returns an S, then it's not an lvalue, and since c is part of the  
struct, it's also not an lvalue, so the result should be an error.

If a.b returns a ref S, then it's an lvalue, and c is also an lvalue.

I think the compiler already restricts you from assigning to rvalues, so  
it could be extended.

An opAssign example:

struct S2
{
    private int *refdint;
    void opAssign(int x) {*refdint = x;}
}

if a.b.c returned an S2, even as a temporary, then it should be allowed.   
Unfortunately, even if the opAssign simply stores the result inside the S2  
struct, then you still need to allow it, because the compiler cannot tell  
what the opAssign is going to do.

> It's a classic problem with properties that are implemented as functions.

Is there another implementation that allows this to work magically?  I've  
only ever seen properties as functions.

> I don't see how C#'s special property syntax adds any value for dealing  
> with this.

And I don't see why it should, or where anyone said it would.  The syntax  
only helps to allow the author to explain what a property is.

Note that most types in C# are reference types, so for the most part,  
there is no issue.

> One thought I had was to simply disallow the '.' to appear after a  
> function style property.

Then you forbid struct types that wrap a reference from being returned, or  
 from affecting ref types that were returned.

-Steve



More information about the Digitalmars-d mailing list