최대 1 분 소요

class MyArray{
public : 
	int size;
	int* data;
	MyArray(int size);
	MyArray(const MyArray& other);
	~MyArray();
};

MyArray::MyArray(int size){
	this->size = size;
	data = new int[size];
}
//복사 생성자
MyArray::MyArray(const MyArray& other){
	this->size = other.size;
	this->data = new int[other.size];
	for (int i =0; i<size; i++)
		this->data[i] = other.data[i];
}

MyArray 클래스 생성자 내에서 new를 사용하여서 정수를 저장 할 수 있는 동적 메모리를 할당 하였다.

int main(){
	MyArray buffer(10);
	buffer.data[0] = 1;
{
	MyArray clone = buffer;
}
	buffer.data[0] = 2;
}

복사 생성자가 없다면, 자신과 같은 클래스 타입의 다른 객체로 자신을 초기화 할 시 2개의 객체가 하나의 동적 메모리를 공유하게 된다. 위에 코드에서, 블록이 종료되면서 지역 변수인 clone 소멸 되는데 동시에, 동적 메모리가 해체 되어 버린다. 한마디로 클론 따위가 죽으면서 본체를 공격한 것이다. 이를 방지하기 위해 복사 생성자가 사용된다.


깊은 복사와 얕은 복사


쉽게 말해 복사시에 같은 동적 메모리를 공유하면 깊은 복사이고, 복사 생성자를 이용해 다른 동적메모리를 할당해 사용하면 깊은 복사이다.

image

태그:

카테고리:

업데이트: