C Support for 'finally' Blocks and the RAII Idiom
Contrary to popular belief, C does not support 'finally' blocks. Instead, it employs a fundamental concept known as RAII (Resource Acquisition Is Initialization).
The RAII Idiom
RAII encapsulates the idea that a resource should be acquired during object initialization and released in its destructor. When an object goes out of scope, its destructor is automatically invoked, ensuring resource cleanup even in the presence of exceptions. This eliminates the need for explicit 'finally' blocks.
An example is illustrated below:
class lock { mutex& m_; public: lock(mutex& m) : m_(m) { m.acquire(); } ~lock() { m_.release(); } }; class foo { mutex mutex_; public: void bar() { lock scopeLock(mutex_); // Lock object foobar(); // May throw an exception // scopeLock will be destructed and release the mutex, regardless of an exception } };
Furthermore, RAII simplifies class management of resources. When member objects manage resources, the owning class can minimize its destructor's responsibility, relying on the destructors of its member objects to release resources.
RAII vs C#'s 'using' Statement
Similar to RAII, C#'s 'using' statement ensures deterministic destruction of resources. However, RAII differs by extending resource management to all resource types, including memory. In contrast, 'using' statements in .NET deterministically release resources except for memory, which is handled during garbage collection cycles.
The above is the detailed content of Does C Have 'finally' Blocks, and How Does RAII Compare to C#'s 'using' Statement?. For more information, please follow other related articles on the PHP Chinese website!