Scope with Brackets in C++

后端 未结 5 1866
滥情空心
滥情空心 2020-12-01 17:50

Is there any case in which putting code within brackets to reduce its scope is something that I might want to do, or is this one of those cases in which you guys will tell m

5条回答
  •  臣服心动
    2020-12-01 18:36

    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 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.

提交回复
热议问题