const ref in opAssign

Jonathan M Davis jmdavisProg at gmx.com
Tue Jun 26 10:19:34 PDT 2012


On Tuesday, June 26, 2012 18:32:37 monarch_dodra wrote:
> 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.

Unlike in C++, a const ref (or const T& in C++) will not accept rvalues. The 
only difference between ref and const ref is that const ref takes const 
lvalues. There has been some discussion on changing this, but apparently there 
are some issues that arise from accepting rvalues for const& the way that C++ 
does which we were trying to avoid, so const ref does not accept rvalues.

As for "you wouldn't be able to assign a const member variable's value of rhs 
to a non-const member of this," the problem is that D's const is transitive. 
Once part of an object is const, _everything_ that it refers to is const, and 
casting away const and mutating the object is undefined behavior (unlike 
C/C++). This provides much stronger guarantees for const and is required to 
properly support immutable, but it _is_ more restrictive. This means that if 
you have a const object and you want to assign it to a non-const object, if 
it's not a value type, the _only_ way to do it without subverting the type 
system is to create a deep copy. So, if you have

struct S
{
 T* value;
}

the opAssign for S would have to make a deep copy of value rather than simply 
assigning rhs' value to S' value. That's not entirely unlike C++ (especially 
if you're not casting away const in C++) - and you often want to make a deep 
copy anyway - but the additional strictness of D's const makes it so that 
there are more cases where you have to worry about and work around constness 
than you would in C++.

- Jonathan M Davis


More information about the Digitalmars-d mailing list