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.
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.
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