C++ - initializing variables in header vs with constructor

前端 未结 7 893
盖世英雄少女心
盖世英雄少女心 2021-01-31 02:00

Regarding the following, are there any reasons to do one over the other or are they roughly equivalent?

class Something
{
    int m_a = 0;
};

v

7条回答
  •  醉梦人生
    2021-01-31 02:45

    The two code snippets you posted are not quite equal.

    class Something
    {
        int m_a = 0;
    };
    

    Here you specify the value with which to initialise, i.e. 0, at compile time.

    class Something
    {
        int m_a;
        Something(int p_a);
    };
    
    Something::Something(int p_a):m_a(p_a){ ... };
    

    And here you do it at run time (or possibly at run time), with the value p_a not known until the constructor is called.

    The following piece of code comes closer to your first example:

    class Something
    {
        int m_a;
        Something();
    };
    
    Something::Something() : m_a(0) { /* ... */ };
    

    What you have to consider here is that in the first case, the value appears directly in the class definition. This may create an unnecessary dependency. What happens if you need to change your 0 to 1 later on? Exposing the value directly in the class definition (and thus, usually, in a header file) may cause recompilation of a lot of code in situations where the other form of initialisation would avoid it, because the Something::Something() : m_a(0) part will be neatly encapsulated in a source file and not appear in a header file:

    // Something.h - stable header file, never changed
    class Something
    {
        int m_a;
        Something();
    };
    
    // Something.cpp - can change easily
    Something::Something() : m_a(0) { /* ... */ };
    

    Of course, the benefits of in-class initialisation may vastly outweigh this drawback. It depends. You just have to keep it in mind.

提交回复
热议问题