copying the targets of pointers

Simen Kjaeraas simen.kjaras at gmail.com
Fri Jul 27 10:45:59 PDT 2012


On Fri, 27 Jul 2012 19:28:06 +0200, monarch_dodra <monarchdodra at gmail.com>  
wrote:

> I'm kind of confused, because every time I see pointer usage, the  
> deference operator is omitted?
>
> For example:
>
> --------
> struct S
> {
>      void foo(){};
> }
>
> S* p = new S();
> p.foo();
> --------
>
> When and where can/should/shouldn't I dereference?

Whenever you need to. :p

Instead of having both . and ->, D has only ., and it derefences for
you, when it needs to.

In terms of other D features, we could imagine pointers being
implemented thus:

struct Pointer(T) {
     T* payload; // Yes, it's a pointer. I *could* use some other
                 // type and reinterpret_cast it, but I won't. :p

     @property
     ref T get() {
         return *payload;
     }

     alias get this;

     // Add operator overloading and all sorts of other magic here.
}


This also means that (*foo).bar() is exactly the same as foo.bar().

The only times you need to derefence is when you need direct access
to the pointee, not just its members. That usually means when you
pass it as a parameter, but also when you have multiple indirections,
or if you're going bit-fiddling.

-- 
Simen


More information about the Digitalmars-d-learn mailing list