Skip to main content

Posts

Showing posts with the label RAII

RAII and Smart Pointers - Resource Management in C++

RAII stands for Resource Acquisition Is Initialization. What is it and why it is needed? We used different resource in out software such as file streams, network pipes, database connections and even locks are considered as resources. The standardized procedure of using a resource is to acquire the resource, use it and then release it. Holding onto resources is bad practice and starves other processes for resources slowing down the entire system in multicore systems. OK, what's the big deal? So we want to open a file, write some stuff to it and then close it. We just do. file.open(); file.write("test"); file.close(); Caution here. If it's a trivial task where you don't have anything in between opening and closing the file (or any other resource) this seems fine but this is often not the case. You have many other things that you do between you opening the file and closing the file. Chances are these operations might fail, or worse throw. In such case ...