To my understanding of the subject: A shallow copy is when the non-pointer types of an object are copied to another object. Shallow copies can't be done when an object has pointers because, the object being copied will get the address of that pointer, and when either of the two objects are deleted, the other will be left dangling since they were pointing to the same location in memory. A deep copy is used when pointers are involved because it reserves a space separate from the original object's space and just copies the contents from one memory location to another. This way, when one of the objects is deleted, teh other isn't left dangling. That said, I would like to know why this program is working even though I've done a shallow copy of a pointer
struct aStruct {
int *i;
aStruct(int *p) : i(p) {
cout << "Created aStruct" << endl;
}
aStruct(const aStruct &s) {
cout << "Copying aStruct" << endl;
i = s.i;
}
aStruct &operator=(const aStruct &s) {
cout << "Assigning aStruct" << endl;
i = s.i;
return *this;
}
};
int main() {
int *x = new int(3);
aStruct s1(x);
aStruct s2 = s1;
int *y = new int(4);
aStruct s3(y);
s3 = s1;
}
s1, s2, and s3 all have their variable i pointing to the same place. So when the end of the main() function is reached and one of them is destroyed, shouldn't the others be left dangling causing an error? My program works fine. Could someone please be kind enough to explain this to me?
Thanks all