• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

소멸자 호출 질문

22.06.21 19:05 작성 조회수 280

0

제가 따라 하면서 좀 다르게 코드를 만들어서 돌려봤는데

소멸자가 왜 한번만 호출이 되는지가 이해가 안되서요

제가 생각에는 re의 소멸자랑 re2의 소멸자 그리고 re3에서 만들어진 복사생성자에서 호출하는 Resource(source.length); 여기서만든 생성자랑 re3에서 만들어진 거랑해서 총 4의 소멸자가 호출이 되어야 한다고 생각하는데 1개만 호출이 되서요 왜그런건가요?

답변 1

답변을 작성해보세요.

0

강민철님의 프로필

강민철

2022.06.22

말씀하신대로 소멸자는 네 번 호출되는 것이 맞는 듯 합니다.

다만 작성하신 코드에 문제가 있는지 살펴보시는 것이 좋을 것 같습니다.

실제로 작성하신 아래 코드를 그대로 따라 돌려보았을 때

 

#include<iostream>
using namespace std;

class Resource {
private:
	int * m_data;
	int length;

public:
	Resource() {
		cout << "Resource is Created" << endl;
	}
	
	Resource(int num) : length(num) {
		cout << "Resource Custom Constructor Created" << endl;
		m_data = new int[length];
	}

	Resource(Resource& source) {
		cout << "Copy Custom Constructor Created" << endl;
		Resource(source.length);

		for (int i = 0; i < source.length; i++) {
			m_data[i] = source.m_data[i];
		}
	}

	~Resource() {
		cout << "Resource is Destroyed" << endl;
		if (m_data != nullptr)
			delete m_data;
	}

	Resource& operator = (Resource& res) {
		if (&res == this) return *this;
		if (this->m_data != nullptr) {
			delete m_data;
		}

		m_data = new int[res.length];

		for (int i = 0; i < res.length; i++) {
			m_data[i] = res.m_data[i];
		}
	}

};



int main()
{
	Resource re(5);
	Resource re2(10);
	Resource re3(re);

	return 0;
}

 

(종료되기까지 조금의 딜레이가 있을 뿐 아니라)

아래와 같이 정상 종료되지 않습니다.

 

 

위 상황에 대해서는 아래 링크를 참고 바랍니다.

https://docs.microsoft.com/en-us/answers/questions/379441/error-code-34exited-with-code-107374181934.html