-
C++) destructorC++ 2022. 11. 23. 18:11
https://www.inflearn.com/course/following-c-plus/dashboard
홍정모의 따라하며 배우는 C++ - 인프런 | 강의
만약 C++를 쉽게 배울 수 있다면 배우지 않을 이유가 있을까요? 성공한 프로그래머로써의 경력을 꿈꾸지만 지금은 당장 하루하루 마음이 초조할 뿐인 입문자 분들을 돕기 위해 친절하고 자세하
www.inflearn.com
constructor는 instance가 생성될 때 호출되는 반면 destructor는 instance가 메모리에서 해제될 때 호출된다.
동적할당으로 만들어진 경우에는 영역을 벗어나도 자동으로 메모리가 해제되지 않기 때문에 delete으로 메모리를 해제할 때에만 destructor가 호출된다.
destructor를 프로그래머가 직접 호출하는 것은 대부분 경우 권장되지 않는다.
ex1)
#include <iostream> using namespace std; class Simple { private: int _id; public: Simple(const int& id_in) : _id(id_in) { cout << "Constructor " << _id << endl; } ~Simple() { cout << "Destructor " << _id << endl; } }; int main() { Simple* s1 = new Simple (0); Simple s2(1); delete s1; return 0; }
ex2) new로 동적할당을 할 경우 메모리 누수 방지용으로 destructor가 사용된다.
#include <iostream> using namespace std; class IntArray { private: int* _arr = nullptr; int _length = 0; public: IntArray(const int length_in) { _length = length_in; _arr = new int[_length]; cout << "Constructor " << endl; } ~IntArray() { if(_arr != nullptr ) delete[] _arr; } int getSize() { return _length; } }; int main() { while (1) { IntArray arr(10); } return 0; }
'C++' 카테고리의 다른 글
C++) 연산자 오버로딩 (0) 2022.11.24 C++) 클래스 (0) 2022.11.23 C++) 함수 포인터 (0) 2022.11.22 C++) 인수 전달 방법 (0) 2022.11.22 C++) std::array, vector (0) 2022.11.22