Python has context managers, which were added for exactly this purpose.
with alloc_resource() as resource:
resource.use() with alloc_resource() as resource:
resource.use()You complain about having to put initialization into 2 constructors, but there's the flip-side with things like mutexes. In c++, you have to have 2 classes, one for the lock and one for the guard. Whereas with a context-manager, you have one class and the locking code is in the __enter__ and __exit__.
with self.lock:
self.do_stuff()
In that case, I would say that the context-manager is nicer.I haven't done much with mutexes, but doesn't having it split over 2 classes introduce a race condition? Seems like a weird way to implement it to me.
{
Type obj;
// do stuff
}
// obj destructor just ran
C# and other languages have similar paradigms, but they require more attention to detail than a destructor does.