Pointer to data member address

前端 未结 6 1918
挽巷
挽巷 2021-01-02 23:59

I have read (Inside C++ object model) that address of pointer to data member in C++ is the offset of data member plus 1?
I am trying this on VC++ 2005 but i am not getti

6条回答
  •  -上瘾入骨i
    2021-01-03 00:26

    To complement AndreyT's answer: Try running this code on your compiler.

    void test()
    {  
        using namespace std;
    
        int X::* pm = NULL;
        cout << "NULL pointer to member: "
            << " value = " << pm 
            << ", raw byte value = 0x" << hex << *(unsigned int*)&pm << endl;
    
        pm = &X::a;
        cout << "pointer to member a: "
            << " value = " << pm 
            << ", raw byte value = 0x" << hex << *(unsigned int*)&pm << endl;
    
        pm = &X::b;
        cout << "pointer to member b: "
            << " value = " << pm 
            << ", raw byte value = 0x" << hex << *(unsigned int*)&pm << endl;
    }
    

    On Visual Studio 2008 I get:

    NULL pointer to member:  value = 0, raw byte value = 0xffffffff
    pointer to member a:  value = 1, raw byte value = 0x0
    pointer to member b:  value = 1, raw byte value = 0x4
    

    So indeed, this particular compiler is using a special bit pattern to represent a NULL pointer and thus leaving an 0x0 bit pattern as representing a pointer to the first member of an object.

    This also means that wherever the compiler generates code to translate such a pointer to an integer or a boolean, it must be taking care to look for that special bit pattern. Thus something like if(pm) or the conversion performed by the << stream operator is actually written by the compiler as a test against the 0xffffffff bit pattern (instead of how we typically like to think of pointer tests being a raw test against address 0x0).

提交回复
热议问题