c,c++/c++ 관련 개념 및 문법

복사 생성자와 소멸자

YoonJongSeok 2023. 7. 15. 00:52

c++에서 동적 할당을 하려면 new, delete가 있어야한다고 했다.

그런데 클래스에서 동적할당을 하고 있는 것이 있다면 (ex 생성자에서) delete를 해주어야 하는데 해줄 수가 없다.

이것들은 delete로 꼭 해제를 해주어야 하는데 그것을 소멸자에서 해준다. 

 

classname::~classname()
{

	if(this->dynamicValue != NULL)
    {
    	delete dynamicValue;
        //if dynamicValue is array delete[] dynamicValue
    }

}

소멸자는 객체가 사라질 때 호출된다.

 

복사 생성자는 객체 a가 있을 때 다른 객체에서 객체 a를 상수 레퍼런스로 받아오는 것이다.

복사 생성자의 문제는 원본 객체에서 동적 할당 받은 변수가 소멸자에 의해 사라지게 되면 원본을 참조하고 있던 다른 객체들은 사라진 원본을 참조하고 있게 되어 dangling reference문제가 생기게 된다. 이것은 얕은 복사(shallow copy)이기 때문인데, 깊은 복사(deep copy)를 통해 해결해주어야 한다. 

class Marin
{
private:
	char* name;
	int coordinateX, coordinateY;
	int hp;
	int damage;
	bool isAlive;
public:
	Marin(int x, int y, int hp, int damage, const char* name)
		: coordinateX(x), coordinateY(y), hp(hp), damage(damage), isAlive(true)
	{
		this->name = new char[strlen(name) + 1];
		strcpy(this->name, name);
	}
	Marin(const Marin& marine)
	{
		this->coordinateX = marine.coordinateX;
		this->coordinateY = marine.coordinateY;
		this->hp = marine.hp;
		this->damage = marine.damage;
		this->isAlive = marine.isAlive;
		this->name = new char[strlen(marine.name) + 1];
		strcpy(this->name, marine.name); // 소멸자 시 문제 발생 방지
	}

	~Marin()
	{
		delete[] name;
	}
};