Hacker News new | ask | show | jobs
by jronkone 5297 days ago
This must be the 9001st time I read a post by a C++ programmer that doesn't understand that the problem isn't that other languages don't have RAII. The problem is that C++ doesn't have finally/unwind-protect and thus requires RAII to approximate it.
2 comments

> The problem is that C++ doesn't have finally/unwind-protect and thus requires RAII to approximate it.

I don't agree with this statement, at least for finally v RAII: RAII is far superior a tool to deal with scope and resource management, as it requires less work on the part of the resource user and is as a consequence far more secure. It also ties in with C++'s memory semantics and therefore exists "for free", which is nice. Even more so in as messy a language as C++.

RAII has issues, one being composition (a subject on which `finally` is worse, not better) and the second one being "in-place" operations, which `finally` can handle but — at the end of the day — should probably be implemented separately.

`unwind-protect` handles both case very nicely and is therefore — as far as I'm concerned — superior. Although it has an (easily dismissed) "inconvenient" over RAII of adding a special form to the language.

Smalltalk's `BlockClosure#ensure` is also quite nice in that department, though I'd say slightly inferior to `unwind-protect` as building on it is more expensive.

I would use RAII even if it weren't required for C++ exception safety. RAII is convenient and it allows you to write code that is smaller and more solid than it would otherwise be (with or without a "finally").
> RAII is convenient and it allows you to write code that is smaller and more solid than it would otherwise be (with or without a "finally").

You don't know what `unwind-protect` is now do you?

I've looked over what unwind-protect does and to me it doesn't do more than what you can do with a custom RAII like class.

The key thing is that it acts like a wrapper around a try/catch/finally-like block (including other forms of flow control), while allowing you to put arbitrary code in the execute and cleanup portions. You would get the same effect with RAII, most of it would be taken care of for you with the right RAII classes, and if you needed custom code then just write a custom RAII like class or be smart about handling it.

Although the C++ version wouldn't handle C's longjmp and also goto's. But if you use them you're not exactly coding in C++ then.

Not just longjmp and goto, but Objective-C's @throw.

As much as I'm a fan of RAII in C++, it really is a "pure C++" idiom. If a C++ class is needed in Objective-C code that can @throw an NSException, then the C++ cleanup code really has to be invocable explicitly (because the destructor might not be called). For example:

  MyCPlusPlusObject object;
  @try
  {
    ...
  }
  @finally
  {
    object.cleanup();
  }