(ref.doc)rmartin 140395

Next clamage 270395 Prev: jason 170395 Up: Usenet

Newsgroups: comp.lang.c++
From: [email protected] (Robert Martin)
Subject: Re: Re-define myself~!
Date: Tue, 14 Mar 1995 17:57:37 GMT

>>>> Summary, how do I:
>>>> 
>>>>     - Have an Object delete itself,
>>>>     - then re-instantiate itself as a different object time

>But what about when you just want to change the class of the object
>but it would take too much time to construct a new object?  C++
>needs metamorphism, changing an object in place to a slightly
>different class without spending time rebuilding the whole object.

This is possible in C++.  Consider:

void* operator new (size_t, void* v) {return v;} // standard in many
                                                 // implementations.

MyObject o;

o.MyObject::~MyObject(); // invoke destructor.  Does not reclaim
                         // actual storage for o.

new (&o) MyOtherObject;  // calls constructor using storage of o.

Now, make no mistake, this is dangerous.  If MyObject requires less
storage than MyOtherObject then you will crash the stack with this
move.  Or, if you change the above example somewhat and use dynamic
memory allocation, then there are situations where operator delete
could be badly confused.  And in the presence of MI, one would have to
be exceedingly careful about the addresses one passed around with this
technique.  All in all, this technique is not for the faint hearted.

However, if you *really* have to change the type of an object in
place, it is possible.   Take care.

automatically generated by info2www version 1.2.2.8