c++ 소멸자 사용에서 잘못된 부분을 짚어주세요.
글쓴이: cucumbers816 / 작성시간: 목, 2014/09/18 - 12:33오전
#include <iostream> #include <fstream> class KSS{ private: int *class1; int *class2; int *class3; int *class4; public: KSS(std::ifstream &inStream, int k, int n); ~KSS(); }; int main(){ std::ifstream inStream; inStream.open("input.txt"); if(inStream.fail()) { std::cerr<<"input file opening failed\n"; exit(1); } int testCasesNum; inStream >> testCasesNum; int k , n; for(int i = 0 ; i < testCasesNum ; i++){ inStream >> k >> n ; KSS kss(inStream, k, n); kss.~KSS(); } return 0; } KSS::KSS(std::ifstream &inStream, int k, int n){ class1 = new int[sizeof(int)*n]; class2 = new int[sizeof(int)*n]; class3 = new int[sizeof(int)*n]; class4 = new int[sizeof(int)*n]; for(int i = 0 ; i < n ; i++){ inStream >> class1[i]; std::cout<<class1[i]<<std::endl; } for(int i = 0 ; i < n ; i++){ inStream >> class2[i]; std::cout<<class2[i]<<std::endl; } for(int i = 0 ; i < n ; i++){ inStream >> class3[i]; std::cout<<class3[i]<<std::endl; } for(int i = 0 ; i < n ; i++){ inStream >> class4[i]; std::cout<<class4[i]<<std::endl; } } KSS::~KSS(){ delete[] class1; delete[] class2; delete[] class3; delete[] class4; }
for(int i = 0 ; i < testCasesNum ; i++){
inStream >> k >> n ;
KSS kss(inStream, k, n);
kss.~KSS();
}
첫번째 테스트 케이스가 끝나고 두번째 테스트 케이스로 넘어가지 않네요. 제가 무엇을 잘못 한 걸까요?
Forums:
소멸자를 두번 호출하시고 계시네요.
kss 클래스 변수가 for문안에서 선언되기때문에
반복이 끝날때마다 자동으로 소멸자를 호출합니다.
그런데 kss.~KSS() 를 통해 소멸자를 명시적호출하게 되면,
클래스가 소멸되는것이 아닌, 그냥 소멸자 함수안의 내용을 수행하게 됩니다.
따라서 소멸자가 두번호출되는것이죠.
즉, 반복이 끝날때마다 소멸자를 두번 호출하기때문에
이미 해제가 끝난 변수를 또 해제하는것에서 오류가 발생하는듯 싶습니다.
그냥 소멸자 함수 호출부분을 삭제하면 될듯싶네요.
정말 감사합니다. !!
여쭤봤던 것 말고도 잘못된 부분이 있었는지도 몰랐는데.. 감사합니다 ㅠㅠ
덤으로
new int[sizeof(int) * n]이라고 하면 정수 n개가 아니라 정수 (sizeof(int) * n) 개, 다시 말하면 (sizeof(int) * sizeof(int) * n) 바이트의 공간을 할당하게 됩니다.
댓글 달기