简体   繁体   中英

Why are initialization lists preferred over assignments?

Take a look here:

http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/

The author says:

class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;

public:
    Something()
    {
        m_nValue = 0;
        m_dValue = 0.0;
        m_pnValue = 0;
    }
};

While this does not exhibit good style, it is valid within the syntax of the C++ language.

...

What? Why is it not good style? I have always done it that way and it is perfectly readable, compared to what the author suggests which is:

...

class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;

public:
    Something() : m_nValue(0), m_dValue(0.0), m_pnValue(0)
    {
    }
};

...

The first time I read the above i didn't even recognize it as valid syntax. Now i understand there are some cases where you have to use initialization lists, but outside of those cases, why would i use them when assignment seems far easier to read and understand?

If the object has a constructor, then your version calls the default constructor and then calls the assignment operator, which is a waste of time compared to calling the constructor with the values for construction. Some objects don't even have a default constructor.

It makes sense to be consistent with your syntax for all variable types, regardless of whether they actually have constructors or not. If you are writing a class template then you might not even know whether or not they do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM