Is it safe to use the “this” pointer in an initialization list?

前端 未结 3 530
小鲜肉
小鲜肉 2020-12-02 18:38

I have two classes with a parent-child relationship (the Parent class \"has-a\" Child class), and the Child class has a pointer back t

相关标签:
3条回答
  • 2020-12-02 18:51

    The parent this pointer, in "pointer terms", is well-defined (otherwise how would the parent constructor know on which instance is it operating?), but:

    • the fields that are declared after the Child object aren't initialized yet;
    • the code in the constructor hasn't run yet;
    • also, the usual warnings about using virtual members from the constructor apply1.

    So, the parent object in general is still in an inconsistent state; everything the child object will do on construction on the parent object, will be done on a half-constructed object, and this in general isn't a good thing (e.g. if it calls "normal" methods - that rely on the fact that the object is fully constructed - you may get in "impossible" code paths).

    Still, if all the child object do with the parent pointer in its constructor is to store it to be use it later (=> when it will be actually constructed), there's nothing wrong with it.


    1. I.e., virtual dispatch doesn't work in constructors, because the vtable hasn't been updated yet by the derived class constructor. See e.g. here.
    0 讨论(0)
  • 2020-12-02 19:03

    The behaviour is well-defined so long as you don't attempt to dereference the pointer until after the Parent object has been completely constructed (as @Sergey says in a comment below, if the object being constructed is actually derived from Parent, then all of its constructors must have completed).

    0 讨论(0)
  • 2020-12-02 19:05

    Yes. It's safe to use this pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions, directly or indirectly, as the object is not yet fully constructed. The object child can store the this pointer of Parent for later use!

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