Avatar ·

What is RAII (Resource Acquisition Is Initialization) in C++ and why is it needed?

Hello colleagues! I'm learning C++ and constantly hear about RAII, but I can't fully understand this concept. It seems to stand for "Resource Acquisition Is Initialization," but that sounds kind of confusing. I have a specific problem. I'm writing a small class for working with files. Here's my code: ```cpp class FileHandler { public: FileHandler(const char* filename) { file = fopen(filename, "r"); if (!file) { std::cerr << "Failed to open file" << std::endl; } } void readData() { // read data char buffer[100]; fgets(buffer, 100, file); } ~FileHandler() { // here I forget to close the file } private: FILE* file; }; ``` The problem is that I often