Is C++ value of this guaranteed? -
consider have class foo (that not have & operator overloaded) address obtained & operator of class guaranteed have same value this pointer?
in code below equalpointer guaranteed return true? there cases return false (e.g. when considering multiple inheritance)?
class foo { bool equalpointer(const foo * f} { return f==this; } } foo f; f.equalpointer(&f);
the issue 1 of memory layout. standard doesn't guarantee memory layout, in particular doesn't guarantee no offset exists between derived , base class...
for example:
class foo: public boost::noncopyable { public: virtual ~foo(); }; because boost::noncopyable doesn't have virtual method, in gcc (void*)(foo*)&f , (void*)(boost::noncopyable*)&f have different values.
but not matter in practice, because compiler perform necessary adjustments. is, if compare foo* should fine , dandy...
... apart multiple inheritance might break this, if there several foo subobjects in hierarchy.
on other hand, should in 1 of 2 cases:
- either there no hierarchy (no virtual) , can compare address of objects is
- or there hierarchy (and virtual method) , use
dynamic_cast<void*>(&f)address of complete object.
therefore, template method, 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); } (which valid if both t , u have virtual methods)
Comments
Post a Comment