In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?

后端 未结 12 1138
北恋
北恋 2020-11-22 08:16

Internally and about the generated code, is there a really difference between :

MyClass::MyClass(): _capacity(15), _data(NULL), _len(0)
{
}

12条回答
  •  无人共我
    2020-11-22 08:30

    There is a difference between initialization list and initialization statement in a constructor. Let's consider below code:

    #include 
    #include 
    #include 
    #include 
    
    class MyBase {
    public:
        MyBase() {
            std::cout << __FUNCTION__ << std::endl;
        }
    };
    
    class MyClass : public MyBase {
    public:
        MyClass::MyClass() : _capacity( 15 ), _data( NULL ), _len( 0 ) {
            std::cout << __FUNCTION__ << std::endl;
        }
    private:
        int _capacity;
        int* _data;
        int _len;
    };
    
    class MyClass2 : public MyBase {
    public:
        MyClass2::MyClass2() {
            std::cout << __FUNCTION__ << std::endl;
            _capacity = 15;
            _data = NULL;
            _len = 0;
        }
    private:
        int _capacity;
        int* _data;
        int _len;
    };
    
    int main() {
        MyClass c;
        MyClass2 d;
    
        return 0;
    }
    

    When MyClass is used, all the members will be initialized before the first statement in a constructor executed.

    But, when MyClass2 is used, all the members are not initialized when the first statement in a constructor executed.

    In later case, there may be regression problem when someone added some code in a constructor before a certain member is initialized.

提交回复
热议问题