Constructor Initialization List Coding Style

Asked 2 years ago, Updated 2 years ago, 29 views

If there are many member variables, you may want to write a new line and a vertical line when you write an initialization list.
In that case, I was wondering how to write the initialization list, so I summarized it.
Please let me know if there are any advantages, disadvantages, or other ways to write.

主に I mainly use VS2013, 2015 and it is based on that opinion.
*1 Tab 4 space is assumed.

  • Does the colon feel uncomfortable in some people?
  • VisualStudio code shaping is possible with all the indents.
class test_class
{
    test_class():
        a(),
        b( ),
        c( )
    {}

    inta,b,c;
};

  • A comma is at the beginning of the line, so you're not familiar with it?
  • VisualStudio code shaping is possible with all the indents.
class test_class
{
    test_class()
        : a( )
        , b( )
        , c( )
    {}

    inta,b,c;
};

  • The indentation of the first and subsequent variables is out of alignment, so using code shaping will cause it to shift.
class test_class
{
    test_class()
        : a(),
          b( ),
          c( )
    {}

    inta,b,c;
};

c++

2022-09-30 18:23

1 Answers

I think the following description is good.

class test_class
{
    inta = 0;
    intb = 0;
    intc = 0;
};

Initializers using : may have a different order of execution and may cause unnecessary bugs.

class test_class
{
    // It looks fine, but it's an indefinite value other than a.
    test_class():
        a(),
        b(a),
        c(b)
    {}

    // initialized in the order of initialization of c, initialization of b, and initialization of a
    int c, b, a;
};

Also, if there are many member variables, you may forget to initialize, but if you set the rule to initialize everything in this description, you will be able to prevent forgetting to initialize.

If you want to use this document due to compiler firewall or dynamic memory retention issues,

test_class()
{
    foo = new Foo();
    bar = new Bar(foo);
}

Foo*foo=nullptr;
Bar*bar=nullptr;

I think writing without constructor initializer as shown in is more difficult to understand.


2022-09-30 18:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.