Scope with Brackets in C++

后端 未结 5 1848
滥情空心
滥情空心 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:23

    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.

    0 讨论(0)
  • 2020-12-01 18:30

    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.

    0 讨论(0)
  • 2020-12-01 18:32

    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?
    }
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2020-12-01 18:37

    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.

    0 讨论(0)
提交回复
热议问题