c++ - Is it possible to use placement-new to change the type of a polymorphic object? -


is possible use placement-new change type of polymorphic object? if not, in standard prohibits it?

consider code:

#include <new>  struct animal {     animal();     virtual ~animal();     virtual void breathe();     void kill();     void *data; };  struct dead: animal {     void breathe() override; };  void animal::kill() {     this->~animal();     new(this) dead; } 

is calling "kill" ever legal?

update: comments not address (il)legality according standard of programming technique shown here of changing type of object explicit call destructor , applying placement-new new object compatible.

because there interest in why this, can mention use case led me question, although not relevant question asking.

imagine have polymorphic type hierarchy several virtual methods. during lifetime of object, things happen can modeled in code object changing type. there many legal ways program this, example, keeping object pointer, smart or not, , swapping in copy of other type. may expensive: 1 has clone or move original object 1 of different type swap new in.

in gcc, clang, , others, changing type of object can cheap changing virtual table pointer, in portable c++ not possible except constructing in-place object of new type.

in original use case, object not held pointer either.

i know standard says on subject of reusing memory.

[basic.life]/8 if, after lifetime of object has ended , before storage object occupied reused or released, new object created @ storage location original object occupied, pointer pointed original object, reference referred original object, or name of original object automatically refer new object and, once lifetime of new object has started, can used manipulate new object, if:

...

(8.4) — original object derived object (1.8) of type t , new object derived object of type t (that is, not base class subobjects).

in example, call kill() may valid (if happens sizeof(animal)==sizeof(dead), don't think guaranteed), attempts use animal* pointer or animal& lvalue through call made trigger undefined behavior way of accessing object lifetime has ended. assuming stars align , animal subobject of dead overlays original location of original stand-alone animal object, such pointer or lvalue not considered refer former, now-expired latter.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -