SBRM(Scope Bound Resource Management)이 RAII의 다른 이름
: 핵심 개념은 파괴인데 이름이 초기화라 다른 이름이 생김
자원의 안전한 사용을 위해 객체가 쓰이는 스코프를 벗어나면 자원을 해제해 주는 기법
ex) std::unique_ptr<>, lock_guard 의 개념이 여기에 해당
C++에서 heap에 할당된 자원은 명시적으로 해제하지 않으면 해제되지 않지만, stack에 할당된 자원은 자신의 Scope가 끝나면 메모리가 해제되며, 소멸자가 불리는 원리를 이용
-> 자원 관리를 스택에 할당한 객체를 통해 수행
예시)
스마트 포인터는 소유하는 메모리의 할당 및 삭제를 처리한다. 스마트 포인터를 사용하면 클래스에서 명시적 소멸자를 widget 사용할 필요가 없다.
#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
메모리 할당에 스마트 포인터를 사용하면 메모리 누수 가능성이 제거될 수 있다.
'C++' 카테고리의 다른 글
좌측값(lvalue) & 우측값(rvalue) (0) | 2023.10.01 |
---|---|
Condition_Variable(조건 변수) (0) | 2023.09.30 |
std::ranges::range (0) | 2023.09.30 |
좁히기 변환(축소변환) & 확대 변환 (0) | 2023.09.30 |
SFINAE(Substitution failure is not an error) (0) | 2023.09.29 |