12.9 Destructors

주홍영·2022년 3월 17일
0

Learncpp.com

목록 보기
133/199

https://www.learncpp.com/cpp-tutorial/destructors/

destructor, 는 특별한 class member function의 중 하나이다
object가 소멸될 때 실행된다
constructor가 클래스를 initializae하기 위해 존재한다면
destructor는 클래스를 정리하기 위해 존재한다

일반적으로 object가 scope를 벗어나거나 동적 할당된 object를 delete 하면
class destructor가 자동으로 호출된다

간단한 클래스의 경우 default destructor로도 메모리 정리에 문제가 없으나
object가 동적할당 메모리를 가지고 있거나 file 혹은 database를 다루고 있다면 문제가 된다

Destructor naming

constructor 처럼 destructor는 specific한 naming rule이 있다
1. The destructor must have the same name as the class, preceded by a tilde (~).
2. The destructor can not take arguments.
3. The destructor has no return type.

참고로 destructor는 다른 member function을 호출할 수 있다
destructor과 실행이 종료되기 전까지는 object가 파괴되지는 않기 때문에

Constructor and destructor timing

class Simple
{
private:
    int m_nID{};

public:
    Simple(int nID)
        : m_nID{ nID }
    {
        std::cout << "Constructing Simple " << nID << '\n';
    }

    ~Simple()
    {
        std::cout << "Destructing Simple" << m_nID << '\n';
    }

    int getID() { return m_nID; }
};

int main()
{
    // Allocate a Simple on the stack
    Simple simple{ 1 };
    std::cout << simple.getID() << '\n';

    // Allocate a Simple dynamically
    Simple* pSimple{ new Simple{ 2 } };

    std::cout << pSimple->getID() << '\n';

    // We allocated pSimple dynamically, so we have to delete it.
    delete pSimple;

    return 0;
} // simple goes out of scope here

위의 코드의 출력은 다음과 같다

Constructing Simple 1
1
Constructing Simple 2
2
Destructing Simple 2
Destructing Simple 1

첫번째 object는 scope를 벗어나며 destroy되기 때문에
두번째 object보다 늦게 파괴됨을 알 수 있다
두번째 object는 명시적으로 delete를 통해 삭제하고 있다

Summary

constructor와 destructor는 함께 사용되어진다
class는 constructor로 initialize 될 수 있고 destructor로 clean up 할 수 있다
error를 발생시킬 확률을 줄여주고 우리가 클래스를 사용하는데 도움을 준다

profile
청룡동거주민

0개의 댓글