Optimization due to constructor initializer list

后端 未结 8 1763
故里飘歌
故里飘歌 2020-12-13 21:23

Constructors should initialize all its member objects through initializer list if possible. It is more efficient than building the constructors via assign

相关标签:
8条回答
  • 2020-12-13 22:16

    As far as POD types are concerned, the initialization and the assignment should be equivalent, since they are left uninitialized if no initialization is performed explicitly, so the only operation remains the assignment.

    Things are different for classes which have default constructors and assignment operators: instead of creating the object directly in the correct state, first the default constructor has to be called, and then the assignment operator (inside the body of the constructor). This is surely more inefficient than initializing the object with the correct constructor straight from the beginning (two steps instead of one, and the first step - default construction - is usually completely wasted).

    The direct initialization also yields the advantage that you can be sure that, if the execution reached the body of the constructor, all the various fields are already in their "correct" state.

    0 讨论(0)
  • 2020-12-13 22:21

    Well, otherwise you call the default constructor and then perform an assignment. That's one step longer and may get really inefficient depending on the nature of initialization.

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