Shallow copy (mặc định của compiler): copy từng byte — với member là pointer, cả hai object cùng trỏ về cùng vùng nhớ. Giải phóng một cái → cái kia thành dangling pointer.
Deep copy: copy cả nội dung mà pointer trỏ tới — hai object hoàn toàn độc lập.
struct Good {
int* data;
Good(int v) { data = new int(v); }
~Good() { delete data; }
Good(const Good& o) { data = new int(*o.data); } // deep copy
Good& operator=(const Good& o) {
if (this != &o) { *data = *o.data; }
return *this;
}
};Quy tắc ngón tay cái: nếu class tự quản lý tài nguyên (raw pointer, file handle...) → phải định nghĩa cả destructor + copy constructor + copy assignment (Rule of Three).
Shallow copy (compiler default): copies each byte — for pointer members, both objects point to the same memory. Freeing one leaves the other with a dangling pointer.
Deep copy: copies the content the pointer points to — both objects are fully independent.
struct Good {
int* data;
Good(int v) { data = new int(v); }
~Good() { delete data; }
Good(const Good& o) { data = new int(*o.data); } // deep copy
Good& operator=(const Good& o) {
if (this != &o) { *data = *o.data; }
return *this;
}
};Rule of thumb: if a class manages a resource (raw pointer, file handle...) → define destructor + copy constructor + copy assignment (Rule of Three).