Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

Scope with Brackets in C++

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 me, "If you need to do that in your code, then your code is badly written."

For example:

//***CODE****
{
  int foo=stuff;
  //use foo, and then I'm done using it forever
}
//****MORE CODE****
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...