|
Boost : |
From: E. Gladyshev (egladysh_at_[hidden])
Date: 2003-10-11 17:09:27
--- "David B. Held" <dheld_at_[hidden]> wrote:
[...]
> This example is in the standard? Unbelievable.
>
> > [Example:
> > struct B {
> > virtual void f();
> > void mutate();
> > virtual ~B();
> > };
> > struct D1 : B { void f(); };
> > struct D2 : B { void f(); };
> > void B::mutate() {
> > new (this) D2; // reuses storage -- ends the lifetime of *this
> > [...]
>
> You mean to tell me that this exact example is in the
> standard? Where? First, where does ~B() get called?
> Second, how can you be sure in general that *this is the right
> size to hold a D2?
>
Yes, it is in 3.8/5
11) For example, before the construction of a global object of non-POD
class type (_class.cdtor_).
(_expr.dynamic.cast_). [Example:
struct B {
virtual void f();
void mutate();
virtual ~B();
};
struct D1 : B { void f(); };
struct D2 : B { void f(); };
void B::mutate() {
new (this) D2; // reuses storage - ends the lifetime of *this
f(); // undefined behavior
... = this; // OK, this points to valid memory
}
void g() {
void* p = malloc(sizeof(D1) + sizeof(D2));
B* pb = new (p) D1;
pb->mutate();
&pb; // OK: pb points to valid memory
void* q = pb; // OK: pb points to valid memory
pb->f(); // undefined behavior, lifetime of *pb has ended
}
--end example]
The whole "reusing storage - object lifetime" thing is unbelievable. :)
Eugene
__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk