RAII (Resource Acquisition Is Initialization): gắn vòng đời tài nguyên (bộ nhớ, file, lock...) vào vòng đời một object trên stack.
- Cấp tài nguyên trong constructor, giải phóng trong destructor.
- Khi object ra khỏi scope, destructor tự chạy — tài nguyên được trả lại kể cả khi có exception.
cpp
void bad() {
FILE* f = fopen("x.txt", "r");
do_work(); // throw exception → fclose không bao giờ chạy → leak
fclose(f);
}
void good() {
std::ifstream f("x.txt"); // constructor mở file
do_work(); // throw cũng được
} // destructor đóng file tự độngHình dung: thay vì nhớ "mở rồi phải đóng", ta giao việc đóng cho object tự dọn khi rời scope.
Đây là nền tảng của std::unique_ptr, std::lock_guard, std::fstream.
RAII (Resource Acquisition Is Initialization): tie a resource's lifetime (memory, file, lock...) to the lifetime of a stack object.
- Acquire in the constructor, release in the destructor.
- When the object leaves scope its destructor runs automatically — the resource is released even if an exception is thrown.
cpp
void bad() {
FILE* f = fopen("x.txt", "r");
do_work(); // throws? fclose never runs → leak
fclose(f);
}
void good() {
std::ifstream f("x.txt"); // constructor opens file
do_work(); // throwing is fine
} // destructor closes file automaticallyMental model: instead of "open, then remember to close", you hand closing to an object that cleans up when it leaves scope.
This underpins std::unique_ptr, std::lock_guard, and std::fstream.