Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 561
laurisvr Avatar asked May 15 '15 11:05

laurisvr


People also ask

Is it safe to use this in constructor?

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the { body } and even in the initialization list) if you are careful.

Can you call a destructor in a constructor?

When you throw from the constructor, it will call the destructor of any object constructed so far: the member variables and the inherited classes (section 15.2/2). If you call the destructor manually, their destructor will be also called (section 12.4/8).

Can we use this pointer in destructor?

In one word: YES.

Can we call constructor and destructor explicitly?

Yes, it is possible to call special member functions explicitly by the programmer.


2 Answers

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).
like image 143
Mike Seymour Avatar answered Sep 30 '22 12:09

Mike Seymour


There is a good entry on it at the C++ super-faq:

https://isocpp.org/wiki/faq/ctors#using-this-in-ctors

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.

Here is something that always works: the {body} of a constructor (or a function called from the constructor) can reliably access the data members declared in a base class and/or the data members declared in the constructor’s own class. This is because all those data members are guaranteed to have been fully constructed by the time the constructor’s {body} starts executing.

Here is something that never works: the {body} of a constructor (or a function called from the constructor) cannot get down to a derived class by calling a virtual member function that is overridden in the derived class. If your goal was to get to the overridden function in the derived class, you won’t get what you want. Note that you won’t get to the override in the derived class independent of how you call the virtual member function: explicitly using the this pointer (e.g., this->method()), implicitly using the this pointer (e.g., method()), or even calling some other function that calls the virtual member function on your this object. The bottom line is this: even if the caller is constructing an object of a derived class, during the constructor of the base class, your object is not yet of that derived class. You have been warned.

Here is something that sometimes works: if you pass any of the data members in this object to another data member’s initializer, you must make sure that the other data member has already been initialized. The good news is that you can determine whether the other data member has (or has not) been initialized using some straightforward language rules that are independent of the particular compiler you’re using. The bad news is that you have to know those language rules (e.g., base class sub-objects are initialized first (look up the order if you have multiple and/or virtual inheritance!), then data members defined in the class are initialized in the order in which they appear in the class declaration). If you don’t know these rules, then don’t pass any data member from the this object (regardless of whether or not you explicitly use the this keyword) to any other data member’s initializer! And if you do know the rules, please be careful.

like image 45
Goz Avatar answered Sep 30 '22 11:09

Goz