[Please do not mail me a copy of your followup]
Paul <
peps...@gmail.com> spake the secret code
<
92d74fb1-3877-4de9...@googlegroups.com> thusly:
>I realise that this was not intended as a c++ question, but I can't see
>a way to do this in c++ because of the huge generality of the question,
>even though I have a basic understanding of deep copying. Can anyone
>help me get an answer in c++ (or help me understand the answers that are
>already provided.)?
In C++, whether one is doing a "shall copy" or a "deep copy" is up to
the implementor of the data structure in how they implement their copy
constructor/assignment operation or in other member functions that
they provide.
For example, here is a structure that will do a "deep copy" when you
use the compiler's supplied copy constructor/assignment:
#include <iostream>
#include <memory>
#include <string>
#include <string>
struct p
{
int i;
std::string s;
};
void doing_deep_copy()
{
p p1{10, "hello, there!"};
p p2 = p1; // deep copy
p2.s = "goodbye!";
std::cout << "p1.s = '" << p1.s << "'\n";
std::cout << "p2.s = '" << p2.s << "'\n";
}
struct q
{
int i;
std::shared_ptr<std::string> s;
};
void doing_shallow_copy()
{
q q1{10, std::make_shared<std::string>("hello, there!")};
q q2 = q1; // shallow copy
*q2.s = "goodbye!";
std::cout << "q1.s = '" << *q1.s << "'\n";
std::cout << "q2.s = '" << *q2.s << "'\n";
}
int main()
{
doing_deep_copy();
doing_shallow_copy();
return 0;
}
The output of this program is:
p1.s = 'hello, there!'
p2.s = 'goodbye!'
q1.s = 'goodbye!'
q2.s = 'goodbye!'
doing_deep_copy is a "deep copy" because after p2 is constructed, it
isn't sharing the string p2.s with p1.s -- they are distinct strings.
However, doing_shallow_copy is a "shallow copy" when you use the
compiler's supplied copy constructor/assignment because it just copies
the members over and the member is a shared pointer to a string.
If you want struct q to have deep copy semantics, you can either
override the compiler-supplied copy constructor/assignment or you can
write a separate member function, most often called 'clone', that
explicitly implements the deep copy operation. Some folks prefer the
'clone' approach because when they see simple = style assignment they
can assume the same semantics as those supplied by the compiler:
memberwise copying.
Unlike a language like JavaScript, you don't have reflection
capabilities in C++, so you can't "dig into the object" being copied
in a generic way and recursively duplicate everything that implies
referenced storage.
--
"The Direct3D Graphics Pipeline" free book <
http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <
http://computergraphicsmuseum.org>
The Terminals Wiki <
http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <
http://legalizeadulthood.wordpress.com>