范围与括号在C + + [英] Scope with Brackets in C++

查看:124
本文介绍了范围与括号在C + +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有任何情况下,放置代码在括号内减少其范围是我可能想做的,或者是这些情况下,你们会告诉我,如果你需要在你的代码,那么你的代码写得很糟。



例如:

  // *** CODE **** 
{
int foo = stuff;
//使用foo,然后我永远使用它
}
// ****更多的代码****


解决方案

是的,因为这样做的优点是,该块中的任何局部变量都将在块。如果你想要尽快发布一些范围保护,例如

  {
std :: lock_guard< std :: mutex> lock(the_mutex);
//使用受保护对象
} //释放the_mutex

,使用像这样的范围块表示您的代码需要重构:块的内容通常可以拆分为一个单独的函数,可以命名和重用。


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

解决方案

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.

这篇关于范围与括号在C + +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆