얕은 복사는 ‘주소만 복사’, 깊은 복사는 ‘내용까지 새로 복사’하는 차이다.
C++에서 복사 생성자를 어떻게 구현하느냐에 따라 객체가 ‘얕게 복사’될 수도 있고 ‘깊게 복사’될 수도 있다.
특히 포인터 멤버(int*)를 가진 클래스라면 둘의 차이가 결과에 큰 영향을 준다.
class MyArray {
public:
int size;
int* data;
MyArray(int size) {
this->size = size;
data = new int[size];
}
// 얕은 복사 생성자
MyArray(const MyArray& other) {
this->size = other.size;
this->data = other.data; // 주소값만 복사됨
}
};
class MyArray {
public:
int size;
int* data;
MyArray(int size) {
this->size = size;
data = new int[size];
}
~MyArray() {
delete[] data;
}
// 깊은 복사 생성자
MyArray(const MyArray& other) {
this->size = other.size;
this->data = new int[size]; // 새 메모리 확보
for (int i = 0; i < size; i++) {
this->data[i] = other.data[i]; // 데이터 자체 복사
}
}
};
| 구분 | 얕은 복사 | 깊은 복사 |
|---|---|---|
| 포인터 복사 방식 | 주소값만 복사 | 새 메모리 생성 후 값 복사 |
| 두 객체 관계 | 같은 데이터를 공유 | 완전히 분리된 개별 객체 |
| 수정 시 영향 | 서로에게 영향 있음 | 서로 영향 없음 |
| delete 실행 시 문제 | 매우 큰 문제 발생 (중복 해제 위험) | 안전 |