When is it safe to call this-> in constructor and destructor

后端 未结 3 1977
遥遥无期
遥遥无期 2020-12-04 21:53

I\'ve not been able to find a conclusive answer to this so far. When is it safe to call this-> from within an object. And in particular from inside the const

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 22:13

    Within any non-static member function, this points to the object that the function was called on. It's safe to use as long as that's a valid object.

    Within the body of a constructor or destructor, there is a valid object of the class currently being constructed. However, if this is the base sub-object of some derived class, then only the base sub-object is valid at that time; so it's generally not safe to down-cast and try to access members of the derived class. For the same reason, you need to be careful calling virtual functions here, since they are dispatched according to the class being created or destroyed, not the final overrider.

    Within the initialiser list of a constructor, you'll need to be careful only to access members that have been initialised; that is, members declared before the one currently being initialised.

    Up-casting to a base class is always safe, since base sub-objects are always initialised first.

    For the specific examples you just added to the question:

    • case 1 is fine (if fragile), since a has been initialised at that point. Initialising a with the value of b would be undefined, since b is initialised after a.
    • case 2 is fine: all members have been initialised at that point.
    • case 3 won't compile, since there's no suitable foo constructor. If there were, then it would depend on what that constructor did with it - whether or not it tried to access members before they were initialised.
    • case 4 would be well-formed if you added the missing ), but dangerous if you tried to use the pointer to access the object. this does not yet point to a valid bar object (only the foo part has been initialised) so accessing members of bar could give undefined behaviour. Simply checking whether the pointer is non-null is fine, and will always give true (whether or not you apply a pointless cast).

提交回复
热议问题