RAII (Resource Acquisition Is Initialization) is a C++ idiom that manages the lifetime of resources (files, memory, sockets, etc.) through the lifetime of objects. Resources are acquired in the object’s constructor and released in the destructor.
#include <fstream> void save_data(const std::string& filename, const std::string& data) { std::ofstream file(filename); // RAII: file will close automatically if (!file) throw std::runtime_error("Cannot open file"); file << data; } // file will close here
In the case of exceptions, the destructor will still be called, and resources will not leak. If RAII is not used, you might face memory and file descriptor leaks.
Can using only try/catch guarantee no memory leaks in C++?
No, it cannot. Simply using try/catch does not guarantee resource release. Only RAII provides that guarantee.
int* arr = new int[10]; try { // Work with arr throw std::runtime_error("Oops"); } catch (...) { // arr not freed, if there was no delete[] } // arr leaked!
Story
In a large graphics project, crashes occurred periodically due to exhaustion of file descriptors. It turned out that files were opened in functions without being wrapped in RAII (std::fstream), and upon throwing an exception, resources were not released.
Story
In a web server request handler, raw memory was used without being wrapped in a smart pointer – in case of an exception, memory was not released, leading to performance degradation and crashes.
Story
In an image processing project, temporary files were created without being wrapped in objects. Upon throwing exceptions, files were not deleted, leading to /tmp overflow on the server after several months of continuous operation.