Taking a copy of an object
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Thu Aug 3 06:26:08 PDT 2006
Derek Parnell wrote:
> Currently there doesn't seem to be any standard D mechanism (read:
> operator) to take a copy of an object. So are there any suggestions for a
> name that we can all agree on; one that might become an unofficial
> standard?
>
> For arrays we have the 'dup' property but for objects there is nothing that
> the compiler assumes. I'm partial to 'onDup' or 'onCopy', and maybe even a
> 'onDeepCopy' as an additional function.
>
> Example:
>
> class Foo
> {
> int x;
> Bar b;
>
> this(int y)
> {
> x = y;
> b = new Bar(y);
> }
>
> Foo onCopy()
> {
> Foo t;
> t = new Foo(x);
> return t;
> }
> }
>
> . . .
>
> auto backup = q.onCopy();
>
What's the "on" prefix for? I think the name should be something like:
dup()
Clone()
Copy()
and it should exist by default in the Object class, with a default
implementation that does a shallow copy.
Also, it is redundant to specify a shallow copy function for each class:
the code is the same for any class. It is something like:
Object ShallowCopy(Object obj) {
int len = obj.classinfo.init.length;
auto data = (cast(ubyte*) obj)[0..len];
return cast(Object) data.dup.ptr;
}
So there should not be two different functions for each kind of copy,
there should be only one, which conceptually is defined to do a deep copy.
> And maybe one day (hoping against precedent) that Walter will actually see
> that an operator for copying stuff is not such a stupid idea.
>
> auto backup := q; // invokes q.onCopy() if it exists.
>
Yes, I think that would be quite useful.
--
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list