C++ RAII Pattern | Resource Management Idiom

C++ RAII Pattern | Resource Management Idiom

이 글의 핵심

Apply RAII to memory, files, locks, and any resource with release semantics.

RAII ties into broader C++ design pattern material in overview #20-2 and creational patterns #19-1 (object lifetime and construction).

What is RAII?

Resource Acquisition Is Initialization: bind resource lifetime to object lifetime.

{
    std::lock_guard<std::mutex> lock(mtx);
    // mutex released at scope end, even on throw
}

Smart pointers

std::unique_ptr, std::shared_ptr — memory RAII.

Mutexes

std::lock_guard, std::unique_lock — lock RAII.

Custom RAII

class File {
    FILE* f;
public:
    explicit File(const char* path) : f(std::fopen(path, "r")) {
        if (!f) throw std::runtime_error("open");
    }
    ~File() { if (f) std::fclose(f); }
    File(const File&) = delete;
    File& operator=(const File&) = delete;
};

  • Smart pointers
  • Mutex

Keywords

C++, RAII, resource management, smart pointers, exceptions