-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
IntArray 클래스 변수인 int_array의 소멸자가 왜 호출되는건가요?
23.09.27 19:58 작성 조회수 129
1
#include <iostream>
#include <cassert>
#include <initializer_list>
using namespace std;
class IntArray
{
private:
unsigned m_length = 0;
int* m_data = nullptr;
public:
IntArray(unsigned length)
:m_length(length)
{
m_data = new int[length];
}
// initializer_list have not support [ ] operator.
IntArray(const std::initializer_list<int>& list)
: IntArray(list.size())
{
int count = 0;
for (auto& element : list)
{
m_data[count] = element;
++count;
}
//for (unsigned count = 0; cout < list.size(); ++count)
// m_data[count] = list[count]; // error
}
~IntArray()
{
delete[] this->m_data;
}
// TODO : overload operator =
/*IntArray& operator = (const IntArray& arr)
{
if (this == &arr)
return *this;
delete[] m_data;
m_length = arr.m_length;
if (arr.m_data != nullptr)
{
m_data = new int[m_length];
for (unsigned i = 0; i < m_length; ++i)
m_data[i] = arr.m_data[i];
}
else
m_data = nullptr;
return *this;
}*/
friend ostream& operator << (ostream& out, IntArray& arr)
{
for (unsigned i = 0; i < arr.m_length; ++i)
out << arr.m_data[i] << " ";
out << endl;
return out;
}
};
int main()
{
int my_arr1[5] = { 1,2,3,4,5 };
int* my_arr2 = new int[5] {1, 2, 3, 4, 5};
auto il = { 10,20,30 };
IntArray int_array{ 1,2,3,4,5 };
cout << int_array << endl;
int_array = il;
cout << int_array << endl;
return 0;
}
질문글이 좀 지저분해서 먼저 죄송합니다.
대입 연산자 오버로딩을 하지 않을 경우에, int_array = il;
대입 연산에서 에러가 나길래, 디버그를 해보니까 int_array 의 소멸자가 호출되어서 메모리공간이 그대로 없어지더라고요..
그런데 제 개념상으로는 int_array 변수가 main 함수의 local 변수인데, 아직 프로그램이 끝나지않았는데도 왜 소멸자가 호출되는건가요?
답변을 작성해보세요.
1
Soobak
2023.09.28
안녕하세요, 답변 도우미 Soobak 입니다.
다음과 같은 과정 때문에 소멸자가 호출되는 것입니다.
int_array = il;
코드 라인에서il
은intArray
자료형이 아니므로,IntArray
자료형의 임시 객체를 생성하게 됩니다.임시 객체는
int_array
에 대입되면서 해당 위치의 데이터를 대체합니다.대입이 끝나면서 임시 객체가 소멸되고, 이 과정에서 소멸자가 호출됩니다.
깊은 복사를 할 수 있도록 대입 연산자를 오버로딩(주석 처리된 코드) 하시는 것으로 해당 문제를 해결하실 수 있습니다.
답변 1