DIP 1008 Preliminary Review Round 1

Stanislav Blinov via Digitalmars-d digitalmars-d at puremagic.com
Fri May 19 12:00:49 PDT 2017


On Friday, 19 May 2017 at 18:10:50 UTC, H. S. Teoh wrote:
> On Fri, May 19, 2017 at 05:48:55PM +0000, Stanislav Blinov via 
> Digitalmars-d wrote:
>> On Friday, 19 May 2017 at 17:05:09 UTC, H. S. Teoh wrote:
> [...]
>> > AFAIK, there is no way to clone classes, unless the class 
>> > writer implemented it explicitly. Only arrays support .dup, 
>> > no other type does (unless user code explicitly implements 
>> > it, or its equivalent).
>> > 
>> > 
>> > T
>> 
>> Well, not that it's a complete implementation or anything, but 
>> it definitely could be done with a library:
>> 
>> /// Make a shallow clone of a class instance
>> /// (members that are classes are not cloned)
> [...]
>
> That's the problem right there: you cannot guarantee that a 
> shallow copy will have the correct semantics.  For example, 
> modifying a class member through the original copy will also 
> modify what is seen through the clone, which may not be the 
> intention.

That's true.

> Also, you have to take care that if the class member is 
> ref-counted, the clone function needs to increment the 
> refcount, otherwise you could end up with a dangling pointer.

It does call postblits. But of course, a complete implementation 
should do more than that. It probably has to lock the monitor for 
the duration, correctly annotate the GC block if memory is being 
GC-allocated, etc...

> Meaning, in the general case, you need to be careful about 
> calling postblits and such.
>
> Furthermore, a generic deep-copying clone function may not be 
> possible in the general case...

Of course. For such cloning to be officially supported by the 
language, at least one additional primitive is needed: __postblit 
for classes. This will let user code correctly handle cloning as 
needed. Surely, a much better solution would be actual 
owning/non-owning pointers and references, but I doubt we'd ever 
get there.



More information about the Digitalmars-d mailing list