Brace placement after init list in C++

自古美人都是妖i 提交于 2019-12-08 18:21:23

It seems important to be able to detect where the ctor-initializer list begins/ends, and where the code block begins/ends.

Object::Object ()
  : foo (1)
  , bar (2)
{
  ...
}
Andru Luvisi

I like to have as much code on the screen as possible at once, so that my eyes can jump back and forth with as little scrolling as possible. There is, of course, a limit. Once I start needing to hunt too hard for something within a line, I have reached a point of diminishing returns. If I'm not initializing more than 3 or 4 fields, I usually do something like this.

Object::Object() : foo(1), bar(2) {
    stuff();
}

If I need to initialize lots of fields, it tends to look like this.

Object::Object() : foo(1), 
                   bar(2),
                   baz(3) {
    stuff();
}

I would guess that most developers like to remain consistent with their bracket formatting with how they are using it in the rest of their code. It's hard enough to read a bracket format that is not your own style. Trying to decipher a mixed format would make your program even more unreadable to someone who is not familiar to your code.

I put the opening brace on a new line. The result looks mostly like the 2nd example, but without the indentation of the initializers.

That said, as this seems to be the part of C++ that has the widest range of layouts in practice, personally I've gone back to initializing variables in the constructor (where still efficient) in order to avoid offending anybody.

I am admitted inconsistent globally in lots of things I do, meaning I do not have one global brace method, instead each language construct may have its own brace method which I use consistently.

 function()
 {
 }

 control-flow () {
 } else {
 }

 type name {
 };

As a constructor is a function...

 foo::foo()
  : bar(1)
  , baz(2)
 {
 }

Here is my style:

Object::Object()
        : foo(1),
          bar(2) {

    // First line here.
}

It remains consistent with my bracket style, but also establishes a visual separation between the initializers and the code.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!