Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 545
Jimmy R.T. Avatar asked Jan 25 '23 04:01

Jimmy R.T.


1 Answers

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.

like image 111
Bathsheba Avatar answered Jan 29 '23 14:01

Bathsheba