Re: Threads on class,

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Carl Daniel [VC++ MVP] (cpdaniel_remove_this_and_nospam_at_mvps.org.nospam)
Date: 10/24/04


Date: Sat, 23 Oct 2004 20:25:46 -0700

Carl Daniel [VC++ MVP] wrote:
> After more experimentation, I have to admit that I was wrong - the
> VC++ compiler actually goes to great pains to make this undefined
> behavior "work" by generating thunks that deal with all of the
> different cases correctly.

I wasn't entirely wrong - it's just a bit more subtle than I thought.

The compiler does go to great pains to make sure that the hack will always
call the right function. It does not, however, guarantee that the correct
function will be called with the correct 'this' pointer.

Here's an example of the kind of construct that fails:

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <stdio.h>

template<class T>
inline void StartMemberThread(T &t, DWORD (__stdcall T::*pmfnMember)())
{
  DWORD ThreadId;
  CreateThread(NULL, 0, * (LPTHREAD_START_ROUTINE *) &pmfnMember, &t, 0,
&ThreadId);
}

struct B
{
   virtual void f() {};
};

struct C
{
   int m_i;
   C(int i) : m_i(i) {}

   DWORD __stdcall MemberThread()
   {
      printf("In A::MemberThread %d\n",m_i);
      return 0;
   }
};

struct A : B, C
{
 A(int i) : C(i) {}
};

void main()
{
        A a(5);
        StartMemberThread<A>(a, A::MemberThread);
        Sleep(100);
}

If you reverse the order of inheritance of A to C, B then it will "work".

-cd



Relevant Pages

  • Re: Threads on class,
    ... I have to admit that I was wrong - the ... DWORD ThreadId; ... virtual void f; ...
    (microsoft.public.vc.language)
  • avoid cast to derived
    ... userBase objects, ... struct Base{virtual void method=0;}; ... virtual void user1(Base& obj){obj.method;} ...
    (comp.object)
  • Maximizing speed of a switch block
    ... We have a critical loop which looks like this: ... virtual void doIt; ... struct allMyVars ... void action_1(X*, allMyVars* v) ...
    (microsoft.public.vc.language)
  • Re: Pattern Protestations.
    ... oops make the pointer derferencing look prettier. ... struct D: X { ... virtual void f ...
    (comp.object)
  • Re: Call to a virtual method crashes
    ... It doesn't matter. ... virtual void f; ... struct Y1: X ... Microsoft MVP - Visual C++ ...
    (microsoft.public.vc.mfc)