Must a reference type be initialized in constructor initialization list?

前端 未结 3 693
夕颜
夕颜 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: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?

提交回复
热议问题