What would be the consequence of implementing interfaces as fat pointers ?

Artur Skawina art.08.09 at gmail.com
Mon Mar 31 07:40:56 PDT 2014


On 03/31/14 15:16, Adam D. Ruppe wrote:
> On Monday, 31 March 2014 at 10:09:06 UTC, Artur Skawina wrote:
>> No. This will bite you once you decide to overload Impl's ops, such as indexing and slicing.
> 
> I agree with you that this is a problem that can bite you, but there's a fairly easy solution: you shouldn't overload Impl's ops, [...]

In real code that pseudo-ref implementation will not necessarily be anywhere near the
payload, and will often be factored out (it makes no sense to duplicate this
functionality in every type that needs it -- so it will be done as 'Ref!T').
Both value- and reference-semantics are very clear and intuitive, but an amalgamate
of reference semantics and pointer arithmetic is a mine waiting to explode; you only
need to forget that your not dealing with a "true reference" for a second. Which is
more likely to happen than not -- when you're dealing with a reference type 'C'
everywhere, it is natural to assume that 'C[10]' works -- that 'C[10]' expression
does not /look/ wrong, so the bug is very hard to spot.


> [...] nor should it have constructors, postblits, or destructors since they won't run when you expect them to either. Putting them on the outer struct works right and opens the door to new things like refcounting too.

Been there, done that. Don't try at home. (Immediately ran into several language
and compiler issues, after working around quite a few ended up with code that
caused data corruption. A compiler that crashes on a block of code, but
accepts that very same block copy&pasted twice, is not fun to deal with... Maybe
things improved in the last two years or so since I did that, but I doubt it.)


>>    struct RefType {
>>       struct Impl {
>>            // put all the stuff in here
>>
>>            @disable this(this);
>>       }
>>       Impl* impl;
>>       ref Impl _get() @property { return *impl; }
>>       alias _get this;
>>
>>       // add ctors and stuff that new the impl
>>    }
> 
> 
> not bad to my eyes,

I think this is as good as it gets, in a language without proper refs.
Still you have ABI issues (passing a struct around can be hadled differently
from the bare-pointer case on some platforms) and the 'Ref!T' syntax is less
than ideal.

artur


More information about the Digitalmars-d mailing list