Wed, 01 Oct 2008 10:23:40 -0700,
Sean Kelly wrote:
> > 3) .dup => .copy
>
> .dup is fine as is, and I think it should always perform a deep copy.
> With D going the direction it is, shallow copies are of limited use and
> can therefore be called .shallow or something.
Deep copy is not possible without knowing the object structure. How
about opDup? :)

On Fri, Oct 3, 2008 at 5:51 AM, Sergey Gromov <snake.scaly@gmail.com> wrote:
> Wed, 01 Oct 2008 10:23:40 -0700,
> Sean Kelly wrote:
>> > 3) .dup => .copy
>>
>> .dup is fine as is, and I think it should always perform a deep copy.
>> With D going the direction it is, shallow copies are of limited use and
>> can therefore be called .shallow or something.
>
> Deep copy is not possible without knowing the object structure. How
> about opDup? :)
How would that differ from a function called dup?
Anyway, copying objects is definitely another place D's story is a little weak.
The class/struct distinction does relieve some of the pressure, but
eventually you will run into situations where you want to copy an
object.
In my code I've been creating polymorphic copy(Type obj) functions
that copy from obj to this. Then implementing dup in terms of copies
like:
Type dup() {
ret = new Type;
ret.copy(this);
return ret;
}
The language could potentially help by automating some of that and
calling an opCopy automatically when "dup" is invoked.
But the above isn't terribly onerous.
Just to be explicit about my understanding of the issues: The basic
problem with just having a dup() is that if Deriv derives from Base
and both implement dup, there's no way for Deriv's dup to use Base's
dup. Both will try to allocate a whole object of their own type. So
dup can't usefully be extended using virtual functions. A copy
function can, though.
void Deriv.copy(Deriv obj) {
// copy from objs fields
this.xxx = obj.xxx ;
// copy super's fields
super.copy(obj);
}
Copying and construction in C++ always seems to be good topics for
tricky interview questions, so there's likely more involved than what
I've just said.
--bb

Sergey Gromov:
> Deep copy is not possible without knowing the object structure. How
> about opDup? :)
An opCopy() / opDeepcopy looks useful (not opDup because in D special names are named about their meaning and not their syntax).
In Python there are the standard special methods __copy__ and __deepcopy__ for that purpose (during deepcopying the system takes care of eventually present loops, this will be important in D too).
Related to the copy, a opGetstate() / opSetstate() may be useful to serialize / deserialize objects on disk.
In Python they of named __setstate__ / __getstate__, when they are present the pickle function uses them, otherwise it just reads/writes all the object attributes.
Bye,
bearophile