Is it legal to explicitly call the base class destructor / constructor?

Is it legal to destroy and build an object of a base class instead of resetting part of the state known to the base class?

class C : public BaseClass {...}; C c; c.BaseClass::~BaseClass(); new (static_cast<BaseClass*>(&c)) BaseClass; 

Clearly, there are other ways to achieve this effect if we have access to the source code of the classes. However, I want to know from a language point of view if there is a specific reason why this is not true.

+5
source share
2 answers

No, this is not legal. You cannot replace the base subobject of an object.

C ++ 11 3.8 / 7 indicates that you can reuse object storage if

the original object was the most derived object (1.8) of type T, and the new object is the most derived object of type T (i.e. they are not subobjects of the base class ).

The object you replaced was a subobject of the base class, not the most derived object, so it is prohibited.

If you were to replace the whole object (i.e. call ~C , and then build a new C ), then this would be legal, but dangerous. If the designer abandoned, then the object will be destroyed a second time at the end of its service life. This will give undefined behavior.

+8
source

The destructor will work (only) if it is virtual, otherwise you will have a partially destroyed object (which seems to be what you really want, given your comments, but not legal). A new place should work, but I'm sure the standard is not allowed by the standard (although I think there is a decent chance that it will work). And I'm not sure why you need this, since the object was derived from C , but after building it would never be C again, only BaseClass .

+2
source

Source: https://habr.com/ru/post/1201405/


All Articles