copying the targets of pointers

Artur Skawina art.08.09 at gmail.com
Fri Jul 27 11:43:45 PDT 2012


On 07/27/12 19:28, monarch_dodra wrote:
> On Friday, 27 July 2012 at 16:47:47 UTC, Artur Skawina wrote:
>> On 07/27/12 18:11, monarch_dodra wrote:
>>> This is going to sound stupid, but how do you have two pointers' targets copy each other? since pointers are used like reference types, how do you write the C++ equivalent of "*p1 == *p2"
>>
>> Exactly the same, there's no difference between C and D pointers, except for classes.
>>
>>> Here is the context of what I'm trying to do:
>>>
>>> ----
>>> struct S
>>> {
>>>   struct Payload
>>>   {}
>>>   Payload payload;
>>>
>>>   @property
>>>   typeof(this) dup()
>>>   {
>>>     typeof(this) ret;
>>>     if(payload)
>>>     {
>>>       ret.payload = new Payload;
>>>       ret.payload = payload; //Copies the payload? The pointer?
>>
>> 'ret.payload' is 'S'; 'new Payload' is '*S'...
>>
>> If you meant 'Payload* payload;', then just the pointer is copied.
>>
>> artur
> 
> Dang it, yes, I meant:
>>   struct Payload
>>   {}
>>   Payload* payload;
> 
> And I want to copy the value pointed by payload. Not the pointer.

      Payload* p = new Payload;
      *ret.payload = *p;

or just

      *ret.payload = *new Payload;


> 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?

The C '.' and '->' operators are folded into just one D op -- the '.'.
So everywhere where you'd write 'p->foo' in C/C++ you just do 
'p.foo' in D. Since both '->' and '.' C ops wouldn't make sense in
the same context, the compiler will do the right thing automagically.

artur


More information about the Digitalmars-d-learn mailing list