linux环境下,强地址转换会在O3的时候出问题

正确的代码如下,


#include <stdio.h>
#include <stdlib.h> 

#include <new> 

#include <string.h> 

class class1 

{ 

public: 

    class1() 

    { 

        b = 10; 

    } 

    int memfunc1(int a) 

    { 

        printf("memfunc1 this %p\n", this); 

        return a - b; 

    } 

private: 

    int b; 

}; 


template <typename F> 

F fkvoidcastmemfunc(void * p) 

{ 

    return *(F*)p; 

} 


void* mymalloc(size_t size) 

{ 

    printf("mymalloc %d\n", size); 

    return malloc(size); 

} 


template <typename F> 

void * fkmemfunccastvoid(F f) 

{ 

    void * p = mymalloc(sizeof(F)); 

    new(p) F(f); 

    return p; 

} 


typedef int (class1::*func1)(int); 

int main(int argc, const char *argv[]) 

{ 

    class1 * p = new class1; 

     

   
 func1 f = &class1::memfunc1;
    (p->*(f))(2); 

    printf("f %p %d\n", f, sizeof(func1)); 

     

    void * pp = fkmemfunccastvoid(f); 

    printf("pp %p\n", pp); 

    func1 fff = fkvoidcastmemfunc<func1>(pp); 

    printf("fff %p\n", fff); 

         

    if (f == fff) 

    { 

        printf("f == fff\n"); 

    } 

    else 

    { 

        printf("f %p != fff %p\n", f, fff); 

    } 

     

    (p->*(fff))(2); 

     

    return 0; 

}