Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ value of this guaranteed?

Tags:

c++

this

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);
like image 645
CiscoIPPhone Avatar asked Dec 02 '10 21:12

CiscoIPPhone


2 Answers

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:

  • either there is no hierarchy (no virtual) and then you can compare the address of objects as is
  • or there is a hierarchy (and virtual method) and you use 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)

like image 58
Matthieu M. Avatar answered Oct 13 '22 23:10

Matthieu M.


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.

like image 21
Edward Strange Avatar answered Oct 13 '22 23:10

Edward Strange