#include <iostream>
class Shallow {
private:
int* data;
public:
Shallow(int d);//생성자
Shallow(const Shallow& source);//복사 생성자 (객체 복사용)
~Shallow();//소멸자
};
int main()
{
Shallow obj1{ 100 };
displayShallow(obj1);//복사 생성자 호출
return 0;
}
Shallow::Shallow(int d) {
data = new int;
*data = d;
}
Shallow::~Shallow() {
delete data;
std::cout << "free storage" << std::endl;
}
//displayShallow() 정의 되어있다고 가정한다.
포인터 주소를 복사하는 것이 아니라, 데이터를 복사하여 복사 생성
복사 생성자가 새로운 힙 공간을 할당하여 동일한 데이터 생성
#include <iostream>
class Deep {
private:
int* data;
public:
Deep(int d);
Deep(const Deep& source);
~Deep();
};
int main() {
return 0;
}
Deep::Deep(int d) {
data = new int;
*data = d;
}
Deep :: ~Deep() {
delete data;
std::cout << "free storage" << std::endl;
}
Deep::Deep(const Deep& source) { //Deep 복사 생성자
data = new int;
*data = *source.data;
}
Deep :: Deep(const Deep& source){
:Deep(*source.data)
{
}