laurisvr laurisvr - 1 month ago 7
C++ Question

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

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 constructor and destructor.

And also, when using public inheritance. Is it safe to use up and downcasting on the result of the this call?

So for example:

class foo
{
foo():
a(),
b(this->a)//case 1
{
this-> a = 5; //case 2
}

int a;
int b;
};

class bar: public baz
{
bar():
baz(this)//case 3 - assuming baz has a valid constructor
{


}

}


And finally the most unlikely one

foo()
{
if(static_cast<bar*>(this));//case 4
}


Which of the above cases are legal?

Note: I'm aware a lot of the practices above are inadvisable.

Answer

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).
Comments