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

后端 未结 12 1155
北恋
北恋 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

    Yes. In the first case you can declare _capacity, _data and _len as constants:

    class MyClass
    {
    private:
        const int _capacity;
        const void *_data;
        const int _len;
    // ...
    };
    

    This would be important if you want to ensure const-ness of these instance variables while computing their values at runtime, for example:

    MyClass::MyClass() :
        _capacity(someMethod()),
        _data(someOtherMethod()),
        _len(yetAnotherMethod())
    {
    }
    

    const instances must be initialized in the initializer list or the underlying types must provide public parameterless constructors (which primitive types do).

提交回复
热议问题