Re: Constructing Derived in shell of Base <shudder>
"Kai-Uwe Bux" <jkherciueh@gmx.net> wrote in message
news:i1nqd9$fhn$1@news.doubleSlash.org...
cpp4ever wrote:
[...]
may I suggest the following
//---------------------
struct B { int j; virtual void f() { std::cout << "B::f\n"; } virtual
~B() {} };
struct D : B { virtual void f() { std::cout << "D::f\n";} };
int main()
{
char obj[sizeof(D)];
B *p = new (obj) B;
p->f(); // B::f() involked
p->~B();
B *p = new (obj) D;
Probably, the above was meant to be:
p = new (obj) D;
Nice idea: assigning a new value to p circumvents [3.8/7] as no old
pointer
to corps is in continued use.
p->f(); // D::f() involked
p->~B(); // D Destructor will be called
}
//---------------------
This still requires care, as before creating an object with new, any
previously created object should be destroyed. Worse still the object
will not automatically be destroyed when it goes out of scope. Therefore
IMHO this sort of functionality should be encapsulated within a class
that ensures things are handled safely.
Just a question: does the standard guarantee that obj is correctly
alligned
for objects of type D and B?
No, take a look at my variant class which can (in addition to its contained
element) be safely placed on the stack:
http://i42.co.uk/stuff/variant.h
Notice the "max_align" union at the top which is the traditional way of
solving this problem.
/Leigh