readonly?

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 11 16:23:57 PDT 2012


On Wednesday, July 11, 2012 09:51:37 Ali Çehreli wrote:
> On 07/11/2012 08:52 AM, David Nadlinger wrote:
> > I fail to see anything inconsistent here.
> 
> Most other operations act on the object:
> 
> class B
> {
> // ...
> }
> 
> auto b = new B();
> 
> ++b; // on the object
> b > b; // on the object
> // etc.
> &b; // on the reference
> 
> That can be seen as an inconsistency. Perhaps it is that the
> non-overridable operators are on the class reference?

It's the fact that in the type system B is a reference to the class named B, 
_not_ the class itself. ++b operates on the object itself, because it's not 
legal to increment a reference. Such an operation makes no sense. Almost all 
operations get forwarded to the object just like using . with a pointer gets 
forwarded to the pointee.

One of the few operations which makes sense on the reference itself is &, 
since it gives you the address of the reference. On the other hand, it makes 
no sense to take the address of the object itself, since there is _no way_ in 
the type system to refer to that object, and the type system purposefully 
makes it so that you don't and can't mess with class objects directly, since 
it avoids problems such as object slicing.

So, while it may seem odd at first that & operates on the reference itself 
rather than the object, remember that the fact that a reference uses a pointer 
is an implementation detail which is _not_ represented in the type at all. 
Think of it like this:

struct S
{
 //opDispatch defined here and
 //all overloaded operators defined here to forward to *ptr...

private:
 C* ptr;
}

S s;

&s would naturally refer to s, not ptr, and there's no way to access ptr 
directly. What engenders so much confusion is that in D's type system, S is 
referred to as C, so you essentially get

struct C
{
 ...

private:
 C* ptr;
}

C c;

where C refers to the struct everywhere except with ptr, which refers to the 
actual class object.

So, while some of the behaviors with regards to classes may seem odd at first, 
they're actually _very_ consistent with everything else.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list