Demonstrate the opAssign() problem for struct template
text/x-dsrc
835
Comments
Comment #0 by pwil3058 — 2013-06-04T23:50:09Z
Created attachment 1219
Demonstrate the opAssign() problem for struct template
The opAssign() operator is not called when the assignment is part of a variable
declaration for both the case where auto used and where the type is declared
explicitly. e.g.:
TestStruct t1 = TestStruct(arg);
TestStruct t2 = t1;
the opAssign() operator is not called in either of these cases. But:
TestStruct t3;
t3 = TestStruct(arg);
t3 = t1;
the opAssign() operator is called in both cases.
This can have serious consequences if (for instance) the purpose of the
opAssign() method being defined was to ensured that the assignee and the
assignor did not share the same internal array.
The attached code demonstrates the problem.
Comment #1 by devw0rp — 2013-06-05T00:03:13Z
Isn't this exactly the same as not calling operator= in C++? I expect this behaviour, because assignment and initialisation are two separate concepts. If you have a case to handle where initialisation copies or destroys another object's memory, do it in this().
Comment #2 by issues.dlang — 2013-06-05T00:08:35Z
This is completely expected. Variable declarations do not use the assignment operator, and
int a = 1;
does not use the assignment operator at all. It's only assignments which use the assignment operator. e.g.
a = 5;
When the variable is declared, it is initialized, not assigned to. While they may seem similar and have similar syntax, they are fundamentally different. And as w0rp points out, this behavior is exactly the same as C++'s behavior.
Comment #3 by pwil3058 — 2013-06-05T16:14:39Z
I should have been clearer. I agree that it is the expected and desirable behaviour when the initializer is an rValue but disagree when it is an lValue.
Comment #4 by issues.dlang — 2013-06-05T17:13:09Z
Sorry, but it's still invalid.
auto foo = bar;
will _never_ use opAssign. opAssign is for overloading the assignment operator, and there is no assignment operator in that statement. It's a variable declaration, not an assignment. Whether it's an lvalue or rvalue is irrelevant for that. The difference is that with an rvalue, it's a move operation, whereas with an lvalue, the postblit operator will be called. So, if you want to overload the behavior of
auto foo = bar;
then you need to declare a postblit constructor:
http://dlang.org/struct.html#StructPostblit