The implicit 'this' parameter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct test
{
        void func()
        {
                std::cout << (void*)this << std::endl;
        }
};
 
int main()
{
        auto f (&test::func);
        auto g ((void(*)(test&))f); //line A
        test t;
        (t.*f)();
        g(t); //line B
}
I'm concerned about whether this is guaranteed to work all the time or if this may not work on some implementations. For the two I tried it printed the same address twice, but I do not know if there were any problems with it.
Is the this pointer passed as the first parameter or last parameter like this? Would my cast be const test& for a const member function?
No this is not guaranteed to work.
I believe this is misguided thinking - the fact that you get the addrees of T is
accidental/co-incidence.
The function g is expecting a reference to a test object - as we are all know that technicallyin theory references take up no space/memory - but
again we all know that passing references to function involves secretly passing
a pointer to the object.

So all in all - this is NOT gauaranteed to work - it all depends on how the compiler
actually implement references (the C++ standard says that this is implementation dependent).

So you were not getting a true this pointer - just an accidental one.
closed account (zb0S216C)
Try using a union. unions are sometimes used to convert. Like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Test
{
    Test *This(void)
    {
        return(this);
    }
};

void *Convert(Test *pPtr = 0x0)
{
    union Conv_Unit
    {
        void *mOut_;
        Test *mIn_;
    };

    Conv_Unit Temp = {pPtr};
    return(Temp.mOut_);
}

Wazzak
Last edited on
What you are trying to do is what I like to call "too clever for your own good". It won't always work, and it's actually very "iffy" to try.

If you need to make a pointer to a member function, just do it the "normal" way and take a member function pointer.
I was just curious.

Last question: is it guaranteed to work if I passed a pointer to a test by value? (I did not originally mean to use a reference; it was, as was said, accidental luck)
Last edited on
Topic archived. No new replies allowed.