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;
}
'C++ > Tips' 카테고리의 다른 글
[c++ 11]Range based for (0) | 2021.06.10 |
---|---|
[c++]Overloading vs Overriding (0) | 2021.06.04 |
Call by value vs Call by reference (0) | 2021.05.28 |
[c++/vector]emplace vs push_back (0) | 2021.03.30 |
[C/C++] #define , #undef (0) | 2021.03.23 |