Optimization due to constructor initializer list

后端 未结 8 1792
故里飘歌
故里飘歌 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.

提交回复
热议问题