On Apr 19, 1:16 am, xtrigger...@[EMAIL PROTECTED]
wrote:
> Thanks a lot to all.
>
> I got Lance point.
> But I just want to get the address of the first enclosing object.
> I'm not interested in the dynamic type of an object that may have
> derived from this "first encloser".
> ( Hope my english is good enough ).
If you don't care at all about the dynamic type of the object, then it
may work in practice.
> PLUS, I do not understand why this technique should not work with non
> POD types.
It ultimately depends on the compiler. For example, popular
implementations of multiple and virtual inheritance involve member
reordering. Consider the following example :
#include <cassert>
#include <cstddef>
struct COuter {
char mPad1[ 5 ];
int mInner;
char mPad2[ 5 ];
};
struct Base : public virtual COuter {
int b;
};
struct Derived :public Base, public virtual COuter {
int d;
};
void* GetEnclAddrFromInner ( int * inner )
{
return (void*) ( (char*)inner -
offsetof(COuter, mInner) );
}
void CheckPointers ( void* true_ptr, COuter * obj ) {
assert( true_ptr == GetEnclAddrFromInner( &obj->mInner ) );
}
int main()
{
COuter a;
Derived b;
CheckPointers( (void*)&a, &a ); #1
CheckPointers( (void*)&b, &b ); #2
}
Line #1 will probably be ok, while line #2 probably won't pass the
assertion, depending on the compiler.
Alexandre Courpron.
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|