+ 1
what is the difference between shallow copy and deep copy??
It will be good ifvu provide in points
2 Answers
+ 1
Thanks
0
This typically refers to a naive copying of pointer/reference members of classes/structs, especially when overriding an object's assignment operator as well as the copy constructor.
For a somewhat simplistic example, lets consider these structs:
struct A{};
struct B{
int i;
A* pA;
};
A a;
B b1;
b1.pA = &a;
A shallow copy would be a function like this:
void shallowCopy(B* dst, B* src) {
dst.i = src.i;
dst.pA = src.pA; //Just copying the pointer value 'as is'
}
After this:
B b2;
shalllowCopy(&b2, &b1);
Both b1 and b2 object's pA member will now point to a.
OTOH, a deep copy would be a function like this:
void deepCopy(B* dst, B* src) {
dst.i = src.i;
A* p = new A;
dst.pA = p; //construct a new/different object for pA
}
After this:
B b2;
deepCopy(&b2, &b1);
Each object's pA member will now point at a different object.