Le 20/03/12 20:44, Denys Duchier a écrit :
Yves Jaradin<[email protected]> writes:
not sure what you mean here. could this have to do with the placement
argument to the new operator?
new (ptr) X(v1,...,vn)
That is related to it. Basically if you have an A* and want a B*, you have to
find out the beginning of the memory block in which A is, give that to the
placement new and hope that the numeric value of the pointer you get back is
equal to the one you started with.
you can overload new where appropriate:
void* operator new(size_t,void* p) { return p; }
That is guaranteed to be the behaviour of placement new on non-arrays,
no need to overload it.
Finding the beginning of the memory for the
A object is implementation specific and error-prone if one wants to consider
all cases including when the dynamic type of the object pointed to is a
subclass of A.
since we are talking about polymorphic classes, dynamic_cast<void*>(p)
is garanteed to return a pointer to the "complete" object containing *p
(you could even used a virtual base class to provide a method to return
that address). you can then pass that pointer as the placement argument
for new.
I did re-read the standard to be sure of where the problems are.
The situation would be as follow:
A class P (probably callled Node or something like that) with virtual
methods and child classes A and B (corresponding to the two concrete
types we are switching from and to).
We start with a P* p that points to an object of actual (most-derived)
class A. The way to do the conversion would be:
dynamic_cast<P*>(new (dynamic_cast<void*>(p)) B(init_params))
But there is no guarantee that the offset of the P subobject in A is the
same as that of the P subobject in B [class.derived]§5, so the pointer
returned by the expression may be different from p. Having P as the
reference type and doing the conversion with
new (reinterpret_cast<void*>(p)) P(init_params) isn't better because the
layout of a base class subobject may be different from the layout of a
most derived object of the same type [class.derived]§8.
Cheers,
--Denys
Cheers,
Yves
_________________________________________________________________________________
mozart-hackers mailing list [email protected]
http://www.mozart-oz.org/mailman/listinfo/mozart-hackers