Is a C ++ value guaranteed?

We believe that I have a class Foo (which does not have it and is overloaded by the operator) - is it the address received from the operator and this class, which should have the same value as its this pointer?

In the code below, is Pointer guaranteed to return true? Are there any cases where it can return false (for example, when considering multiple inheritance)?

 class Foo { bool equalPointer(const Foo * f} { return f==this; } } Foo f; f.equalPointer(&f); 
+8
c ++ this
source share
3 answers

The problem is the memory layout. The standard does not guarantee much in the memory layout, in particular, it does not guarantee the absence of bias between the derived and base class ...

For example:

 class Foo: public boost::noncopyable { public: virtual ~Foo(); }; 

Since boost::noncopyable does not have a virtual method, gcc (void*)(Foo*)&f and (void*)(boost::noncopyable*)&f will have different values.

But in practice this does not really matter, since the compiler will make the necessary settings. That is, if you are only comparing Foo* , you should be fine and dandy ...

... Also, that multiple inheritance can break this if there are several Foo entities in your hierarchy.

On the other hand, you must be in one of two cases:

  • either there is no hierarchy (no virtual) and then you can compare the address of the objects as
  • or there is a hierarchy (and a virtual method), and you use dynamic_cast<void*>(&f) to get the address of the complete object.

Therefore, as a template method, this will 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); } 

(this is true only if both T and U have virtual methods)

+3
source share

With the code in question? Yes.

Are there constructions in which this is not so? Also yes.

But yes, a pointer to an instance of class X will always be equal to the pointer 'this' in class X. The same cannot be said for its base classes or derived classes.

+2
source share

Yes it is.

The pointer f same, and it is passed to f::equalPointer ...

+2
source share

Source: https://habr.com/ru/post/649773/


All Articles