proposal for general dup function

Dan dbdavidson at yahoo.com
Mon Dec 10 12:32:18 PST 2012


On Monday, 10 December 2012 at 20:10:25 UTC, Andrei Alexandrescu 
wrote:

> You want to create a new window with the same parent. At the 
> top level there's one desktop window, and probably having two 
> would be odd.
>

Ok - so I'm only talking about structs.

What you say is what you want here and it makes sense. But that 
is not what I'm proposing. I'm just talking deep copy of structs 
that is always deep copy - period (bearophile called it 
transitive copy). By design that means there is no aliasing at 
all. So in this case the parent window would be deep copied. This 
can be done without any change to the struct (cycles when 
pointers are used are one design issue that would need to be 
addressed). This is also why gdup can be used to copy any 
immutable(T) into T (assuming is(T==struct)) and get around the 
"how do I copy const/immutable instances" we see so often.

Below illustrates what would happen and you would not want it for 
Window parent/child relationships - but you see the consistency. 
For what you describe you want reference semantics and gdup is 
not needed.

Given this - I think the original claim still holds.
     I claim that gidup or igdup or whatever
     can just be:

     @property auto gidup(T)(const ref T t) {
       immutable(T) result = cast(immutable)(t.gdup);
       return result;
     }

I am not saying you can or should gdup any struct instance willy 
nilly, just that the cast to immutable here is safe because all 
fields are deep copied recursively.


------------------- output -------
Window("c1", 5, 5, 7FFF5BF3F4F0)
Window("c1", 5, 5, 7FAC74004FE0)
-------------------
import std.stdio;
import opmix.mix;

struct Window {
   string name;
   int x, y;
   Window *parent;
}

void main() {
   auto window = Window("root", 1, 1);
   auto child = Window("c1", 5, 5, &window);
   auto c2 = child.gdup;
   writeln(child);
   writeln(c2);
}


More information about the Digitalmars-d mailing list