C++/Tips
깊은복사(Deep Copy) vs 얕은복사(Shallow Copy)
메리사츠
2021. 5. 31. 23:02
1. Shallow Copy
=> 참조는 복사가 되지만, 참조되는 객체가 복사되지 않는 복사
=> 쉽게 이야기하면, 참조는 두개가 만들어지지만, 객체가 복사되지 않아서, 1참조에서 값을 변경하면 2참조에서 변경이 되는 것
=> 그렇기 때문에 아래 코드에서 first가 원래 할당하고 있던 공간의 경우 delete가 안되는 현상 발생[공통메모리 참조]
#include<iostream>
using namespace std;
int main()
{
int* first = new int(10);
int* second = new int(15);
cout << "first Addr : " << first << endl;
cout << "second Addr : " << second << endl;
cout << "first : " << *first << endl;
cout << "Second : " << *second << endl;
first = second; // 참조만 복사
*second = 10;
cout << "first Addr : " << first << endl;
cout << "second Addr : " << second << endl;
cout << "first : " << *first << endl;
cout << "Second : " << *second << endl;
delete first;
return 0;
}

2. Deep Copy
=> 참조와 객체 둘다 복사가 되는 복사
=> 쉽게 이야기하면, 참조와 객체 각각 복사되어, 1참조에서 값을 변경하여도 2참조에는 영향을 미치지 않음
#include<iostream>
using namespace std;
int main()
{
int* first = new int(10);
int* second = new int(15);
cout << "first Addr : " << first << endl;
cout << "second Addr : " << second << endl;
cout << "first : " << *first << endl;
cout << "Second : " << *second << endl;
*first = *second; // 깊은 복사
*second = 10;
cout << "first Addr : " << first << endl;
cout << "second Addr : " << second << endl;
cout << "first : " << *first << endl;
cout << "Second : " << *second << endl;
delete first;
delete second;
return 0;
}

