Search code examples
c++pointersraw-pointer

Is the adress behind this guaruanteed to be identical to a variable with the object


In case of the following code:

#include<iostream>

class Sample
{
public:
  Sample* getSelf()
  {
    return this;
  }
};

int main()
{
  Sample s;

  if(reinterpret_cast<void*>(&s) == reinterpret_cast<void*>(s.getSelf()))
    std::cout << "Same address" << std::endl;

  return 0;
}

Is the condition in the if statement guaruanteed to be true?

I've made the cast to void* to be sure that the raw addresses are compared, in case there's some quirks in comparing specific pointer types.


Solution

  • Yes your if statement is guaranteed to be true. The this within getSelf() is the pointer to the instance.

    And &s in main is also a pointer to that instance.

    The casts are unnecessary as you suspect.