Consider I have a class Foo (that does not have its & operator overloaded) is the address obtained from the & operator of this class guaranteed to have the same value as its this
pointer?
In the code below is equalPointer guaranteed to return true? Are there any cases where it could 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 is one of memory layout. The standard doesn't guarantee much about memory layout, in particular it doesn't guarantee that no offset exists between a derived and a base class...
For example:
class Foo: public boost::noncopyable
{
public:
virtual ~Foo();
};
Because boost::noncopyable
doesn't have a virtual
method, in gcc (void*)(Foo*)&f
and (void*)(boost::noncopyable*)&f
will have different values.
But this does not matter much in practice, because the compiler will perform the necessary adjustments. That is, if you only compare Foo*
you should be fine and dandy...
... Apart that multiple inheritance might break this, if there are several Foo
subobjects in your hierarchy.
On the other hand, you should be in one of two cases:
dynamic_cast<void*>(&f)
to get the address of the complete object.Therefore, as a template method, this would 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 is only valid if both T and U have virtual methods)
With the code in question? Yes.
Are there constructs in which this is not so true? Also yes.
But yes, a pointer to an instance of class X is always going to be equal to the 'this' pointer within class X. Same can't be said of its base classes or derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With