Thread overview
[Issue 2701] New: Can't declare struct, assign lvalue to it in same statement
Mar 02, 2009
d-bugmail
[Issue 2701] Can't declare struct, assign lvalue via opAssign in same statement
Mar 02, 2009
d-bugmail
Aug 16, 2010
David Simcha
March 02, 2009
http://d.puremagic.com/issues/show_bug.cgi?id=2701

           Summary: Can't declare struct, assign lvalue to it in same
                    statement
           Product: D
           Version: 2.025
          Platform: PC
        OS/Version: Windows
            Status: NEW
          Keywords: rejects-valid, spec
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: bugzilla@digitalmars.com
        ReportedBy: dsimcha@yahoo.com


struct Bar {
    uint num;

    Bar opAssign(uint otherNum) {
        num = otherNum;
        return this;
    }
}

void main() {
    uint foo = 1;
    Bar bar = foo;  // Error:  e2ir:  cannot cast from uint to Bar.
    Bar bar2;
    bar2 = foo;   // Works.
}

Not sure if this is actually a valid bug, since the spec states that "The assignment operator cannot be overloaded for rvalues that can be implicitly cast to the lvalue type."  However, if the previous sentence does implicitly disallow this from working, it should be stated more clearly, instead of in a single sentence of language legalese.


-- 

March 02, 2009
http://d.puremagic.com/issues/show_bug.cgi?id=2701





------- Comment #1 from daniel.keep+d.puremagic.com@gmail.com  2009-03-01 20:59 -------
You can't use opAssign for initialisation; you have to use opCall. Specifically,

Bar bar = foo;

is rewritten as:

Bar bar = Bar(foo);

which is further rewritten as:

Bar bar = Bar.opCall(foo);

I'm not sure if this is documented explicitly anywhere; I just remember this from when it was implemented.


-- 

August 16, 2010
http://d.puremagic.com/issues/show_bug.cgi?id=2701


David Simcha <dsimcha@yahoo.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
         Resolution|                            |INVALID


--- Comment #2 from David Simcha <dsimcha@yahoo.com> 2010-08-15 21:11:33 PDT ---
I'm closing this, since this appears to be what C'tors are for.  The following example demonstrates.  Perhaps this should be better documented, though.

struct Bar {
    uint num;

    this(uint otherNum) {
        opAssign(otherNum);
    }

    Bar opAssign(uint otherNum) {
        num = otherNum;
        return this;
    }
}

void main() {
    int foo = 1;
    Bar bar = foo;  // Error:  e2ir:  cannot cast from uint to Bar.
    Bar bar2;
    bar2 = foo;   // Works.
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------