Re: Object layout guarantees and manual pointer adjustments
On Apr 16, 7:07 am, SG <s.gesem...@gmail.com> wrote:
Hello!
This is a question on object layout guarantees and whether manual
pointer adjustments can be done safely. What does the C++ standard
say about this:
ptrdiff_t delta(void* from, void* to)
{
return static_cast<char*>(to)
-static_cast<char*>(from);
}
void* adjust(void* in, ptrdiff_t diff)
{
return static_cast<char*>(in) + diff;
}
class A { int a; /* assume non-POD */ };
class B { int b; /* assume non-POD */ };
class C : public A, public B {};
void foo() {
C c;
B* pb = &c;
ptrdiff_t diff_c2b = delta(&c,pb);
C c2;
B* x1 = &c2;
B* x2 = static_cast<B*>(adjust(&c2,diff_c2b));
assert(x1==x2);
}
Is the assertion guaranteed to hold? I believe that it does hold for
all existing implementations but I would like to know whether this is
really guaranteed by the C++ standard.
That particular program may be guaranteed not to trigger that assert,
but there is a gotcha you should know: virtual multiple inheritance.
Depending on the type of the complete object, various base class sub
objects will be positioned differently relative to each other in the
complete object. So for objects of the same complete type, maybe it
will work, but probably not by standard. However, for arbitrary
pointers to objects, thus including pointers to base class sub
objects, no, an assert like the above will not always work on any
implementation for complete objects of different types.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]