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

后端 未结 12 835
北恋
北恋 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:50

    You need to use initialization list to initialize constant members,references and base class

    When you need to initialize constant member, references and pass parameters to base class constructors, as mentioned in comments, you need to use initialization list.

    struct aa
    {
        int i;
        const int ci;       // constant member
    
        aa() : i(0) {} // will fail, constant member not initialized
    };
    
    struct aa
    {
        int i;
        const int ci;
    
        aa() : i(0) { ci = 3;} // will fail, ci is constant
    };
    
    struct aa
    {
        int i;
        const int ci;
    
        aa() : i(0), ci(3) {} // works
    };
    

    Example (non exhaustive) class/struct contains reference:

    struct bb {};
    
    struct aa
    {
        bb& rb;
        aa(bb& b ) : rb(b) {}
    };
    
    // usage:
    
    bb b;
    aa a(b);
    

    And example of initializing base class that requires a parameter (e.g. no default constructor):

    struct bb {};
    
    struct dd
    {
        char c;
        dd(char x) : c(x) {}
    };
    
    struct aa : dd
    {
        bb& rb;
        aa(bb& b ) : dd('a'), rb(b) {}
    };
    

提交回复
热议问题