"Novice" <> wrote in message news:<bgcnc8$80v$>...
> "Mike Wahler" <> wrote in message
> news:bgcmnd$ira$...
> | Novice <> wrote in message
> | news:bgckl0$693$...
> | > Hi all, has there been any research into creating a method (no pun
> intended)
> | > for doing exact bit copies of objects without invoking a copy
> constructor
> of
> | > an object?
> |
> | No need. If you don't define a copy ctor, one
> | will be synthesized for you, which does a member-
> | wise assignment.
> |
> | >
> | > For example:
> | >
> | > class A {
> | > int foo;
> | > public:
> | > A (int foo_):foo(foo_){}
> | > ...
> | > };
> | >
> | > A a1(42);
> | > file://note I'm aware there is no clone function in the standard
> namespace
> | > file://that creates an exact bit copy of an object - this is just an
> example of
> | > how it might work
> | > A a2 = std::clone(a1);
> | >
> | > I don't know enough about how flexible C++ can be in terms of writing a
> | > function like this
> |
> | And how how this be superior to a copy ctor?
>
> It would remove the need to write a copy constructor for each class that you
> write - as you point out the need for a deep copy of an object.
<snip>
>
> | You don't need to unless you need a 'deep copy' etc.
> | It happens automatically in a default copy ctor.
> |
>
>
> Yes - well there you go - that would be a case in which it could be useful.
>
> [snip]
>
> A method of creating deep copies without copy constructors
I think you missed Mike's point [1]. I'm certain you misread Mike's
attitude, but that happens sometimes in this sort of faceless
communication. Not anyone's fault, it just happens.
A clone function couldn't be of any use for deep copies. For example,
if your class has a pointer member, there is no way for clone() to
know how large a chunk of memory it points to. So clone() can't do a
deep copy. If you want a deep copy, you have to write it yourself
because only you know exactly how / whether your class remembers how
much memory it has allocated.
If you want a shallow copy (such that the pointer members of the
source and destination both hold the same value hence point to the
same place, and all other members of the source and destination end up
identical too) then that is precisely what the compiler generated copy
ctor does for you so you don't need clone().
hth
GJD
[1] Alternatively, I might have missed Mike's point. In which case,
the views expressed herein are mine alone and Mike is free to disagree
if he wishes