Taking a copy of an object
Kirk McDonald
kirklin.mcdonald at gmail.com
Thu Aug 3 16:28:25 PDT 2006
Hasan Aljudy wrote:
>
>
> Derek wrote:
>
>> On Thu, 03 Aug 2006 14:12:03 -0600, Hasan Aljudy wrote:
>>
>>
>>> Bruno Medeiros wrote:
>>>
>>>> Derek Parnell wrote:
>>>>
>>>
>>> <Snip>
>>>
>>>>> 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.
>>>>
>>>
>>> Oh please, I hate the := operator, it's too ugly.
>>
>>
>>
>> I don't give a damn what operator is used, this was *JUST AN EXAMPLE*.
>> Please, feel free to suggest other things that might be suitable for a
>> deep-copy operator. One that would be usable on all data types and meants
>> that the information in the left-hand-side thingy would be copied and the
>> right-hand thingy would 'hold' that copy.
>>
>> For objects, it would invoke onDup/onCopy/onClone/onDeepCopy/onWhatever
>> (the name doesn't matter) if it existed, otherwise its a compile time
>> error. The function would return the same datatype as the object that
>> owns
>> the function, meaning that Foo.onDup can't return a Bar or its parent
>> type
>> or an interface - it must return a Foo object instance.
>>
>> For arrays it is identical to the .dup property.
>>
>> For basic datatypes it is identical to moving the bit value from one to
>> another variable (no conversion or transformations allowed).
>>
>> Therefore the lefthand side and righthand side thingy must be the same
>> datatype.
>>
>
> why an operator?
> a method/property is more suitable, I think.
People used to C++ are used to doing this with an operator overload.
People used to some other languages (e.g. Python) will be more used to
using a method (or even a library function, in the case of Python). I
honestly don't think it matters.
One could also argue for the use of copy constructors, of course. This
may be getting too close to C++ for some people's tastes, though. (The
syntax is also more verbose than a simple .dup property.)
class Foo {
int m_i;
this(int i) { m_i = i; }
this(Foo f) { m_i = f.m_i; }
}
Foo a, b;
a = new Foo(20);
b = new Foo(a);
This does have the advantage of using "new" to make it clear that we are
allocating a new object (though I don't think this is really a problem
with just using .dup).
With reflection support, we could even give Object a useful default copy
constructor, as Tom S pointed out.
--
Kirk McDonald
Pyd: Wrapping Python with D
http://dsource.org/projects/pyd/wiki
More information about the Digitalmars-d
mailing list