Yes it works. As soon as you exit the scope, the objects local to that scope will be immediately destroyed.
Yes it is worth it, especially in cases like your example (reducing the lifetime of an object to ensure a resource is released early -- but you can also use it just to reduce the scope of a temporary identifier and make it inaccessible after that, even though this use is a bit less interesting than your example).
Yes there is a (slightly) better alternative: just use braces without the
if
clause:
.
{
std::lock_guard<std::mutex> guard(mResourceMutex);
mResources.insert(ResourceContainer::value_type(id, res);
}
A proper compiler will be able to optimize out the if (true)
so the generated code will be identical, but the braces alone are much cleaner from a style point of view. Additionally the braces alone are a well known and immediately recognizable idiom, while your if (true)
isn't and makes the reader wonder (even if briefly) "what is the purpose of that if? Oh wait, right, it's the usual scope-limiting idiom...".