
On Saturday 15 September 2012 01:13:51 Andrew Sandoval wrote:
Andrey Semashev <andrey.semashev <at> gmail.com> writes:
The probability of exception doesn't matter. Scope guards (or RAIIFunction) are typically used to implement exception safety, so introducing the possibility of exception from the scope guard itself sort of defeats its purpose. At the very least, it will complicate usage - probably, more than it will simplify one. IMHO, this tool should not be based on boost/std::function. I knew someone would say that about the possibility of exceptions. Again, I would argue that the other class doesn't have that problem and is a better fit for most things, but I don't see anyway your going to get std::tr1::function functionality without allocations and the risk of an exception -- unless it is implemented so that an exception can't be thrown.
There are several alternatives to std::function. One has been pointed out in this thread several times - capture the scope guard by reference to base. This is my preferred solution. I can also suggest another option: use fixed sized buffer to place the function object on the stack. The size of the buffer can be specified as a template parameter of the scope guard. This gives you runtime flexibility (which I don't think is necessary) but it makes the code less portable. I personally don't like it, unless you can provide a motivating example where initialization of an already constructed scope guard is required.
I disagree completely about it defeating the purpose. You can find something less than perfect in just about every library, but that doesn't mean they aren't tremendously useful.
It's not just imperfection. It simply disables the main use case of the tool, unless you close your eyes an put a comment "I feel lucky" before the scope guard. If your function-based scope guard is not intended to be used for exception safety then define its purpose. And don't call it RAII because it can't be used for resource management.
Again though, a collection of RAII wrapper classes is what I'm proposing. And the great thing about having them in Boost, besides the fact that I don't have to re-write them over and over, is that all of the caveats can be well documented, as they are in other libraries.
Are we making any progress here? I don't think I'm alone in seeing the value of RAII classes and promoting the practice.
I'm not arguing with that.