GameDevelop

RAII - Resource acquisition is initialization

Une_ 2024. 9. 10. 15:45

 

RAII 라는 키워드에 대해 정리해봅니다.

한창 면접 준비할 때 기억해뒀던 내용인데, 키워드만 다시 보니 기억이 잘 안나서 정리할 필요를 느끼네요.

 

Resource acquisition is initialization

= 리소스 획득은 초기화

 

직역하니 좀 어색합니다.

 

 

리소스를 할당한 뒤 해제하지 않으면 메모리 누수가 발생합니다.

 

개체 (Object) 가 생성될 때 리소스를 할당하고,

                           파괴될 때 리소스를 해제하도록 하면 누수될 일이 없습니다.

 

즉 개체가 리소스를 소유하게 한다는 원칙이 RAII입니다.

 

 

 

아래는 MS 문서에서 가져온 코드입니다.

class widget
{
private:
    int* data;
public:
    widget(const int size) { data = new int[size]; } // acquire
    ~widget() { delete[] data; } // release
    void do_something() {}
};

void functionUsingWidget() {
    widget w(1000000);  // lifetime automatically tied to enclosing scope
                        // constructs w, including the w.data member
    w.do_something();

} // automatic destruction and deallocation for w and w.data

widget의 생성자에서 data 할당을 하고, 소멸자에서 data를 해제하는 것을 볼 수 있습니다.

이러면 widget을 사용한 뒤, 사용된 함수 블록을 벗어나면 소멸자를 호출하면서 할당된 data 메모리가 해제됩니다.

 

 

 

그리고 더 좋은 방법으로... 스마트포인터를 사용하면 관리가 쉬워집니다.

#include <memory>
class widget
{
private:
    std::unique_ptr<int[]> data;
public:
    widget(const int size) { data = std::make_unique<int[]>(size); }
    void do_something() {}
};

void functionUsingWidget() {
    widget w(1000000);  // lifetime automatically tied to enclosing scope
                        // constructs w, including the w.data gadget member
    // ...
    w.do_something();
    // ...
} // automatic destruction and deallocation for w and w.data

스마트 포인터를 사용하면 widget의 명시적 소멸자까지 구현하지 않아도 됩니다.

 

unique_ptr 등 스마트 포인터로 메모리를 할당하면

해당 포인터의 참조 수가 0이 되었을 때 자동으로 해제해주기 때문에 메모리 누수 가능성이 제거될 수 있습니다.

 

 

 

개체 수명 및 리소스 관리(RAII) | Microsoft Learn

 

개체 수명 및 리소스 관리(RAII)

리소스 누수 방지를 위해 최신 C++에서 RAII 원칙을 따릅니다.

learn.microsoft.com