The problem is the memory layout. The standard does not guarantee much in the memory layout, in particular, it does not guarantee the absence of bias between the derived and base class ...
For example:
class Foo: public boost::noncopyable { public: virtual ~Foo(); };
Since boost::noncopyable
does not have a virtual
method, gcc (void*)(Foo*)&f
and (void*)(boost::noncopyable*)&f
will have different values.
But in practice this does not really matter, since the compiler will make the necessary settings. That is, if you are only comparing Foo*
, you should be fine and dandy ...
... Also, that multiple inheritance can break this if there are several Foo
entities in your hierarchy.
On the other hand, you must be in one of two cases:
- either there is no hierarchy (no virtual) and then you can compare the address of the objects as
- or there is a hierarchy (and a virtual method), and you use
dynamic_cast<void*>(&f)
to get the address of the complete object.
Therefore, as a template method, this will give:
template <typename T, typename U> bool have_same_dynamic_location(T const& t, U const& u) { return dynamic_cast<void*>(&t) == dynamic_cast<void*>(&u); }
(this is true only if both T and U have virtual methods)
Matthieu M.
source share