c++ - When is it safe to call this-> in constructor and destructor -
i've not been able find conclusive answer far. when safe call this->
within object. , in particular inside constructor , destructor.
and also, when using public inheritance. safe use , downcasting on result of call?
so example:
class foo { foo(): a(), b(this->a)//case 1 { this-> = 5; //case 2 } int a; int b; }; class bar: public baz { bar(): baz(this)//case 3 - assuming baz has valid constructor { } }
and unlikely one
foo() { if(static_cast<bar*>(this));//case 4 }
which of above cases legal?
note: i'm aware lot of practices above inadvisable.
within non-static member function, this
points object function called on. it's safe use long that's valid object.
within body of constructor or destructor, there valid object of class being constructed. however, if base sub-object of derived class, base sub-object valid @ time; it's not safe down-cast , try access members of derived class. same reason, need careful calling virtual functions here, since dispatched according class being created or destroyed, not final overrider.
within initialiser list of constructor, you'll need careful access members have been initialised; is, members declared before 1 being initialised.
up-casting base class safe, since base sub-objects initialised first.
for specific examples added question:
- case 1 fine (if fragile), since
a
has been initialised @ point. initialisinga
value ofb
undefined, sinceb
initialised aftera
. - case 2 fine: members have been initialised @ point.
- case 3 won't compile, since there's no suitable
foo
constructor. if there were, depend on constructor did - whether or not tried access members before initialised. - case 4 well-formed if added missing
)
, dangerous if tried use pointer access object.this
not yet point validbar
object (onlyfoo
part has been initialised) accessing members ofbar
give undefined behaviour. checking whether pointer non-null fine, , givetrue
(whether or not apply pointless cast).
Comments
Post a Comment