Boost logo

Boost :

From: E. Gladyshev (egladysh_at_[hidden])
Date: 2003-10-11 03:29:22


I know you all are sick and tired of it, but I am not.
Please help me to understand it.
I posted the same question to the c++ news group.

struct my_type
{
   f() {}
};

/*
5.3.4/8 (C++ Standard)
[...]
[Note: since allocation functions are assumed to return pointers to
  storage that is appropriately aligned for objects of any type, this
  constraint on array allocation overhead permits the common idiom of
  allocating character arrays into which objects of other types will
  later be placed. ]
*/

char buf[sizeof(my_type)]; //5.3.4/8 -> can safely allocate my_type in buf

my_type* p1 = new( buf ) my_type;

/*
according to 5.3.4/9
  "The address of the created object will not necessarily be the same as
that
  of the block of storage if the object is an array."

We are not allocating an array, so p1 == buf !!!
*/

p1->f(); //ok

/*
3.8/4
"A program may end the lifetime of any object by reusing the storage
which the object occupies"
*/
my_type* p2 = new( buf ) my_type; //reusing *p1 storage

//NOTE: according to 5.3.4/9, p2 == buf !!!

p2->f(); //ok
p1->f(); //undefined (according to 3.8/4) -- lifetime of *p1 is ended

At this point,
'p2' is equal to 'p1' and they pointing to the same data type,
p1->f() is undefined, so that p2->f() is undefined.

So, p2 = new(buf) my_type; returned a pointer
to an object of 'my_type' type with an undefined
behavior.

I must be doing something stupid. What?

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