Copy constructor in D. Why it is necessary to have it.
Bill Baxter
wbaxter at gmail.com
Thu Oct 2 14:15:00 PDT 2008
On Fri, Oct 3, 2008 at 5:51 AM, Sergey Gromov <snake.scaly at 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
More information about the Digitalmars-d
mailing list