Must a reference type be initialized in constructor initialization list?

前端 未结 3 679
夕颜
夕颜 2020-12-06 12:50

As self-exercise, I have written this simple code:

#include 

int gIndex = 3;

template  class Array
{
public:
    explicit Ar         


        
相关标签:
3条回答
  • 2020-12-06 12:51
    Must any class-member reference type be initialized in the constructor initialization list?
    

    Yes, we should always use initializer list to initialize reference members of a class.

    If so, why? Is that related somehow to the fact that a reference type can never be reassigned?
    

    A constructor has two phases namely initialization and computation. So, even if you don't use initializer list for a data member compiler will initialize it with random value. And in in computation phase which typically starts with the '{' of constructor body, if you do an assignment then compiler will complain as the reference member was already intialized. So, your only chance to initialize such member is the constructor initializer list.

    Are there more types that must be initialized in constructor initialization list?
    

    Yes, const data members are the other type for which you need an initializer list.

    0 讨论(0)
  • 2020-12-06 12:52

    Does any class-member reference type must be initialized in the constructor initialization list?

    Yes.

    If so, why? Is that related somehow to the fact the a reference type can never be reassigned?

    That's part of the reason. The other part is because a reference must be initialized, and it has no default constructor.

    Are there more types that must be initialized in constructor initialization list?

    Any type that doesn't have an assignment operator (be it copy or move) or default constructor. This obviously includes (but is not limited to) const members as they can't be modified once they've been constructed.


    As a rule of thumb, you should (almost) always prefer to initialize your members in the constructor's initialization list: why waste cycles first default-constructing an object and then only assigning to it (if this is even possible), when you could construct it correctly in the first place?

    0 讨论(0)
  • 2020-12-06 13:12

    Must any class-member reference type be initialized in the constructor initialization list?

    Yes.

    Is that related somehow to the fact that a reference type can never be reassigned?

    Yes, plus the fact that there is no "null" or default construction for a reference. It is an alias for another object, and it has to be bound to it from the outset. You cannot do this (this is not inside a class definition):

    int main()
    {
      int& iref; // ERROR
      int i = 42;
      int& iref2 = i; // OK
    }
    

    because iref must alias something.

    0 讨论(0)
提交回复
热议问题