On 04/18/2013 06:22 AM, Joseph Rushton Wakeling wrote:> On 04/17/2013 10:29 PM, Ali Çehreli wrote: >> Yes but as I said I am not sure how useful or needed this whole thing is.
>>
>> The language handles copy, move, and assignment for structs. takeOver() seems to
>> be a primitive operation for classes.
>
> Could you expand a bit on that?  Just that I'm not sure I understand your
> meaning completely, and I'm curious. :-)

Being value types, structs enjoy automatic handling of copy, assignment, and in the case of rvalues, move.

struct S
{
    int i;
}

S makeS()
{
    return S();
}

void main()
{
    auto a = S();
    auto b = a;    // a is copied to b
    b = a;         // a is assigned to b
    b = makeS();   // the returned rvalue is 'moved' to b
}

Of course that works only for structs with simple value members. When the automatic handling is not sufficient or does the wrong thing, then the programmer must provide this(this), opAssign(), or ~this(). Things get more interesting when the members are mutable or immutable references.

With the above definition of S, all of the following compile:

    immutable(S) imm0;
    S mut = imm0;            // immutable to mutable

    immutable(S) imm1 = mut;  // mutable to immutable

    immutable(S) imm2 = imm0; // immutable to immutable

Now naively add another member to S:

struct S
{
    int i;
    int[] arr;  // <-- added
}

Only the latter of the three assignments compile:

    immutable(S) imm0;
    S mut = imm0;             // compilation ERROR

    immutable(S) imm1 = mut;  // compilation ERROR

    immutable(S) imm2 = imm0; // compiles

Anyway... I am trying to wrap up what I have learned so far before going any further. :)

For classes, none of these operations make sense: There is no automatic copying, no automatic assignment, nor there are rvalues to move.

> I'd assumed this problem would be some fairly straightforward aspect of the > language that I just wasn't familiar with, so I'm quite struck by the fact that
> it actually seems a non-trivial problem.

My experience has been with C++ so I don't know how this is solved in Java or C#. Maybe this is not a problem with the common idioms in those languages, which would also mean that this is not a problem with D classes. Rather, if one has decided to go with a class, then value semantics were not a consideration to begin with.

Ali

Reply via email to