On Tuesday, 26 June 2012 at 15:40:48 UTC, Jonathan M Davis wrote:
On Tuesday, June 26, 2012 14:44:45 monarch_dodra wrote:

Depending on your type, taking const ref Widget would be a big problem, because you wouldn't be able to assign a const member variable's value of rhs to a non-const member variable of this (e.g. if it's a class) without making a deep copy. Or it could be just fine. It all depends on your type and what you're trying to do. Regardless, the solution is almost certainly to have
multiple overloads. Each of the overloads does this

// Works with any Widget if Widget is a value type and any non-const Widget
// if it's a reference type.
ref Widget opAssign(Widget rhs) {}

// Works with any Widget as long as you can copy all of the member variables
// when they're const.
ref Widget opAssign(const Widget rhs) {}

// Works with non-const Widgets which are lvalues only.
ref Widget opAssign(ref Widget rhs) {}

// Works with any Widgets which are lvalues as long as you can copy all of the
// member variables when they're const.
ref Widget opAssign(ref Widget rhs) {}

In most cases, I would expect you to have these two overloads

ref Widget opAssign(const Widget rhs) {}
ref Widget opAssign(const ref Widget rhs) {}

It then works with const (as long as you're not dealing with a type which can't really be copied when it's const) and both rvalues and lvalues. The rvalue version must be const to ensure that constness does not affect which overload gets called (just l/rvalue-ness). This is particularly critical if the rvalue version simply calls the lvalue version, because if it's not const,
you'd get infinite recursion.

- Jonathan M Davis

Thanks for the in-depth explanation! It is still not very clear to me, mostly because I don't understand "you wouldn't be able to assign a const member variable's value of rhs to a non-const member variable of this". This works fine in C++. Must be because I've never used a language with reference semantics before.

Either that, or I'm miss-understanding the "ref" keyword. I thought "const ref" meant pass by const reference, but it would appear it means a reference to a const object... or something like that. I'll need to read the chapter on const too.

Either way, I guess I'll have to become more familiar with the language to fully appreciate this.

Reply via email to