Scope with Brackets in C++

Solution 1:

Yes, because this has the advantage that any local variables in that block will be destroyed at the end of the block. This is especially useful if you have some kind of scope guard that you want to release as soon as possible, e.g.,

{
    std::lock_guard<std::mutex> lock(the_mutex);
    // use protected objects
}   // release the_mutex

Note, however, that the use of a scope block like this is indicative of your code needing to be refactored: the contents of the block can usually be split out into a separate function, which can be named and reused.

Solution 2:

I have found another use case in my own code: unit testing destructors. Example using UnitTest++ (but the same principle applies regardless of unit testing framework):

TEST(SomeTest)
{
   {
   SomeClass someObject;
   } // someObject is destroyed
   CHECK(isSomeClassDestructorWorking())
   // e.g. have all resources been freed up?
}

Solution 3:

For example, if you use the RAII idiom this may be useful. Synchronization locks for example.

In most case, the scope of a method should be small enough for such locks. There are times when you want to limit the lock scope for either performance, or to avoid sending a gazillion parameters to a refactored method. Using this trick shouldn't be too common, though.

Solution 4:

With all the things you can do in C++, adding a scope would really be the least of them. There is nothing wrong with the code you have, I do it sometimes (often in a case to ensure the locals are restricted to the case). Depending on the use you may like to think about refactoring the code into a separate function.

Solution 5:

Another place bracket scoping makes sense is inside macros. For example, you could define a macro that declares variables of potentially the same name as variables inside the code block into which the macro is placed.