RAII Resource Acquisition Is Initialization
suggest changeRemarks
RAII stands for Resource Acquisition Is Initialization. Also called scope-based resource management, it ties a resource's lifetime to an object's lifetime. When an automatic object leaves scope, its destructor runs during normal control flow and stack unwinding, allowing resource cleanup to be expressed as object destruction.
Any time you need to acquire some resource (e.g. a lock, a file handle, an allocated buffer) that you will eventually need to release, you should consider using an object to handle that resource management for you. Stack unwinding will happen regardless of exception or early scope exit, so the resource handler object will clean up the resource for you without you having to carefully consider all possible current and future code paths.
It’s worth noting that RAII doesn’t completely free the developer of thinking about the lifetime of resources. One case is a crash or std::abort, which does not run destructors. std::exit does not destroy automatic objects either, though it does destroy objects of static storage duration. Since the OS will clean up process-local resources like memory after a process ends, this is not a problem in most cases. However with system resources (i.e. named pipes, lock files, shared memory) you still need facilities to deal with the case where a process didn’t clean up after itself, i.e. on startup test if the lock file is there, if it is, verify the process with the pid actually exists, then act accordingly.
Another situation is when a unix process calls a function from the exec-family, i.e. after a fork-exec to create a new process. Here, the child process will have a full copy of the parent’s memory (including the RAII objects) but once exec was called, none of the destructors will be called in that process. On the other hand, if a process is forked and neither of the processes call exec, all resources are cleaned up in both processes. This is correct only for all resources that were actually duplicated in the fork, but with system resources, both processes will only have a reference to the resource (i.e. the path to a lock file) and will both try to release it individually, potentially causing the other process to fail.