On Tuesday, 26 June 2012 at 12:44:46 UTC, monarch_dodra wrote:
I just finished reading the chapters on user defined types and,
(as a C++ dev), this one line struc out to me as very odd:
"ref Widget opAssign(ref Widget rhs) {..}"
This means that during an assignment, I could potentially
change "Other" (!). This seems like a blatant violation of the
expected behavior of =. What's more, it prevents the assignment
from a const object...
I am very tempted to change the call to "const ref". Is this
un-advised?
Mr. Alexandrescu goes on to mention a "pass by value" in case
you wanted to assign from a temporary, mentioning:
w = Widget(50); // Error!
// Cannot bind an rvalue of type Widget to ref Widget!
The only problem is that if I do this, all of my calls are then
re-routed to pass by value, and none to the pass-by-const-ref.
----
Is there any way to enforce const correctness, while still
keeping advantage of both calls?
PS: using Mr. Alexandrescu's design, it is not possible to
assign from a const Widget, I get:
hello.d(50): Error: function hello.Widget.opAssign (Widget rhs)
is not callable using argument types (const(Widget))
hello.d(50): Error: cannot implicitly convert expression (w2)
of type const(Widget) to Widget
const can't be passed by value...?
I actually remember having this issue (I'll look up the
reference to it later). The issue was the non-const non-ref
version was a better fit; Now obviously it's wrong, but you can't
convince the compiler of that. If the assign never modifies the
incoming object, then why should you make two versions?
Anyways. Try making 2 versions of opAssign with ref and try it
again: ie a const-ref & non const-ref, and finally your pass by
value.