|
|
|
|
|
by nsmnsf
4480 days ago
|
|
Can someone explain RAII to me? In the way that it's commonly used, it seems like it really means "stack variables that go out of scope are deallocated", which seems kind of, well, duh? I don't really understand why it's treated like a big deal. (I mostly write C + Obj-C) |
|
Consider a C example:
Consider a C# example: Now a C++ example using RAII: These examples are mostly equivalent (Although the C#/C++ assume exceptions instead of error codes).The C#/C++ examples are far more structured and less error prone than the C example.
The advantage of C++'s RAII over C#'s using statement is that cleanup is tied to the object rather than a statement. This means that RAII is both composable and non-leaky as an abstraction. You cannot forget to destruct an object in C++, and you don't have to care that its destructor frees resources. When you have an IDisposable member in C# you must manually mark your class as IDisposable and then implement the Dispose method yourself. Clients must also be aware that your class is IDisposable in order to use it correctly.