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

后端 未结 4 1594
无人共我
无人共我 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:49

    You can find a good answer to this here (C++ FAQ).

    All inherited members and members of the calling class are guaranteed to have been constructed at the start of the constructor's code execution and so can be referenced safely within it.

    The main gotcha is that you should not call virtual functions on this. Most times I've tried this it just ends up calling the base class's function, but I believe the standard says the result is undefined.

提交回复
热议问题