I have come across what seems like a really annoying bug running my C++ program under Microsoft Visual C++ 2003, but it could just be something I'm doing wrong so thought I'd throw it out here and see if anybody has any ideas.
I have a hierarchy of classes like this (exactly as is - e.g. there is no multiple inheritance in the real code):
class CWaitable
{
public:
void WakeWaiters() const
{
CDifferentClass::Get()->DoStuff(this); // Breakpoint here
}
};
class CMotion : public CWaitable
{
virtual void NotUsedInThisExampleButPertinentBecauseItsVirtual() { }
};
class CMotionWalk : public CMotion
{ ... };
void AnnoyingFunctionThatBreaks(CMotion* pMotion)
{
pMotion->WakeWaiters();
}
Okay, so I call "AnnoyingFunctionThatBreaks" with a "CMotionWalk" instance (e.g. the debugger says it's 0x06716fe0), and all seems well. But when I step into it, to the breakpoint on the call to "DoStuff", the 'this' pointer has a different value to the pMotion pointer I called the method on (e.g. now the debugger says one word higher - 0x06716fe4).
To phrase it differently: pMotion has the value 0x06716fe0, but when I call a method on it, that method sees 'this' as 0x06716fe4.
I'm not just going mad am I? That is weird, right?
I believe you are simply seeing an artifact of the way that the compiler is building the vtables. I suspect that CMotion has virtual functions of it's own, and thus you end up with offsets within the derived object to get to the base object. Thus, different pointers.
If it's working (i.e. if this isn't producing crashes, and there are no pointers outside the objects) then I wouldn't worry about it too much.
Is CMotion class is deriving some other class also which contains a virtual function? I found that the this pointer does not change with the code you posted, however it changes if you have the hierarchy something like this:
class Test
{
public:
virtual void f()
{
}
};
class CWaitable
{
public:
void WakeWaiters() const
{
const CWaitable* p = this;
}
};
class CMotion : public CWaitable, Test
{ };
class CMotionWalk : public CMotion
{
public:
};
void AnnoyingFunctionThatBreaks(CMotion* pMotion)
{
pMotion->WakeWaiters();
}
I believe this is because of the multiple inheritance for CMotion class and the vtable pointer in CMotion which points to Test::f()
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