Property assignment problem

Jonathan M Davis jmdavisProg at gmx.com
Fri May 11 00:02:54 PDT 2012


On Friday, May 11, 2012 08:52:14 SebastianA wrote:
> This is related to this thread:
> http://forum.dlang.org/thread/cnwpmhihmckpjhlaszzy@forum.dlang.org
> 
> I am posting it here as well, since it no longer concerns only
> GDC. Also, I am not sure if this is a bug or intended behaviour.
> Consider the following code:
> 
> ====
> void runTest()
> {
> 	Thing t;
> 	t.vPosition = (Clock.currStdTime % 2 == 0) ? Vec(2, 2) : Vec(3,
> 3);
> 	Vec v = t.vPosition;
> 
> 	writefln("%d %d\n", v.x, v.y);
> }
> 
> struct Vec
> {
> 	int x;
> 	int y;
> }
> 
> struct Thing
> {
> 	@property Vec vPosition() { return mPosition; }
> 	@property Vec vPosition( const ref Vec value ) { return
> mPosition = value; }
> 
> private:
> 	Vec mPosition;
> }
> ====
> 
> The line that sets the value of the vPosition property does not
> compile on DMD. Instead it gives the error "Error: not a property
> t.vPosition". On GDC this compiles but it does not work in
> release mode, only in debug mode. In release mode it sets the
> property to 0 0. If I assign the vector to a temp variable before
> assigning it to the position it works. It also works if I replace
> the time expression with a constant like "true" or some other
> value known at compile time.
> 
> Is this a bug or is it supposed to refuse to compile the code?
> Also, why does it compile on GDC?

Remove the ref from the setter. Either that or duplicate it:

        @property Vec vPosition( const Vec value )
        { return  mPosition = value; }
        @property Vec vPosition( const ref Vec value )
        { return  mPosition = value; }

ref does not currently accept rvalues, even if it's const (unlike C++). There 
are issues in C++ caused by the fact that const& parameters can be either 
lvalues or rvalues, so D insists that ref is always an lvalue, even if it's 
const. There has been some discussion of making it possible for ref and const 
ref to take rvalues with some set of restrictions to avoid the problems that 
it causes in C++, but that hasn't been fully sorted out yet.

- Jonathan M Davis


More information about the Digitalmars-d mailing list