Passing “this” to a function from within a constructor?

后端 未结 4 1552
无人共我
无人共我 2021-02-05 02:19

Can I pass \"this\" to a function as a pointer, from within the class constructor, and use it to point at the object\'s members before the constructor returns?

Is it saf

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 02:48

    When you instantiate an object in C++, the code in the constructor is the last thing executed. All other initialization, including superclass initialization, superclass constructor execution, and memory allocation happens beforehand. The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.

    Of course, you still need to beware of uninitialized member variables, if you haven't already initialized them in your constructor code.

提交回复
热议问题