Scope with Brackets in C++

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.

Leave a Comment