C ++代码中的额外括号括号 [英] Extra brace brackets in C++ code

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

问题描述

有时候,你遇到的代码有额外的大括号,与范围无关,只是为了可读性和避免错误。

Sometimes you run into code that has extra brace brackets, that have nothing to do with scope, only are for readability and avoiding mistakes.

例如:

GetMutexLock( handle ) ; 
{
  // brace brackets "scope" the lock,
  // must close block / remember
  // to release the handle.
  // similar to C#'s lock construct
}
ReleaseMutexLock( handle ) ;

其他地方,我看到的是:

Other places I have seen it are:

glBegin( GL_TRIANGLES ) ;
{
  glVertex3d( .. ) ;
  glVertex3d( .. ) ;
  glVertex3d( .. ) ;
} // must remember to glEnd!
glEnd() ; 

这引入了编译器错误,如果互斥体不释放(假设你记住了} Release() call)。

This introduces a compiler error if the mutex isn't freed (assuming you remember both the } and the Release() call).

问题是:


  • 1这是不好的做法吗?为什么?

  • 2如果这不是一个坏习惯,它可能会改变代码的编译方式?

推荐答案

大括号本身很好,你不会减慢任何东西。它可以看作是更清洁。 (总是喜欢干净的代码,快速的代码,如果它更干净,不要担心速度,直到你的个人资料。)

The braces themselves are fine, all they do is limit scope and you won't slow anything down. It can be seen as cleaner. (Always prefer clean code over fast code, if it's cleaner, don't worry about the speed until you profile.)

但是对于资源,这是糟糕的做法,因为你已经让自己处于泄露资源的位置。

But with respect to resources it's bad practice because you've put yourself in a position to leak a resource. If anything in the block throws or returns, bang you're dead.

使用范围绑定资源管理(SBRM,也称为RAII),它将资源限制为范围,通过使用析构函数:

Use Scope-bound Resource Management (SBRM, also known as RAII), which limits a resource to a scope, by using the destructor:

class mutex_lock
{
public:
    mutex_lock(HANDLE pHandle) :
    mHandle(pHandle)
    {
        //acquire resource
        GetMutexLock(mHandle);
    }

    ~mutex_lock()
    {
        // release resource, bound to scope
        ReleaseMutexLock(mHandle);
    }

private:
    // resource
    HANDLE mHandle;

    // noncopyable
    mutex_lock(const mutex_lock&);
    mutex_lock& operator=(const mutex_lock&);
};

所以你得到:

{
  mutex_lock m(handle);
  // brace brackets "scope" the lock,
  // AUTOMATICALLY
}

这样做会所有资源,它更干净,更安全。如果你能够说我需要释放这个资源,你做错了;他们应该自动处理。

Do this will all resources, it's cleaner and safer. If you are in a position to say "I need to release this resource", you've done it wrong; they should be handled automatically.

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

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