const ref in opAssign

Christophe Travert travert at phare.normalesup.org
Tue Jun 26 10:09:50 PDT 2012


"monarch_dodra" , dans le message (digitalmars.D:170728), a écrit :
> 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.

In D, const is transitive. It mean that if an instance is const, 
everything that is refered by this instance is const. Thus, I can't copy 
a reference of a const instance to make a non-const reference.

Example:

struct A
{
  int* x;
  ref A opAssign(const ref other)
  {
    this.x = other.x; // error: other.x, which is a const(int*) because 
                      // of transitivity, can't be assign to this.x 
                      // (which is a non-const int*).
  }
}

You need to write either:
  ref A opAssign(ref other)
  {
    this.x = other.x; // no problem, other.x is not const.
    // Note: the value this.x is now shared between this and other
  }
or:
  ref A opAssign(const ref other) // deep copy
  {
    this.x = new int(*other.x);
    // this is a deep copy: a new int is created to take other.x's value
  }


If the structure contain no references at all, there is no problem, and 
opAssign should be const ref, with a const overload for l-values, as 
previously said.

-- 
Christophe


More information about the Digitalmars-d mailing list