Your first example isn't exception safe. If something throws an exception after the Lock
but before the call to Unlock
you'll never release the lock, which is bad!
For this sort of pattern you should use the RAII approach that you show in your second example. Not only is it exception safe but it saves you having to worry about calling Unlock
, which you could easily forget to do and get some difficult to track down errors.