C++ With Initializer List a thing, when to use normal constructor?

后端 未结 3 840
無奈伤痛
無奈伤痛 2021-01-06 18:50

I just started getting back into C++ here recently and learned about Initializer Lists. It seems to be the standard way to initialize members. That being said I have 2 quest

3条回答
  •  旧时难觅i
    2021-01-06 19:34

    Initialization list is about calling ctor of member variables. If you assign, you are altering the value of instance by using assign function. Obviously, these two are different functions.

    There are a few cases that you cannot assign value to member variable in the ctor.

    • When the member variable is const.
    • When the member variable is an instance of class without default ctor.
    • When the member variable is a reference (same reason as above)
    • Initializing base class

    When you create an instance without init-list, the member variable runs its ctor and then assign if you give value to it. It's a subtle difference but it might incur some penalty as the ctor runs first, and assign runs 2nd - which is unnecessary overhead.

提交回复
热议问题