Pointer function function declared class forward

The common.h forward header declares a Test class and a function that receives a pointer to a member function:

 class Test; void func(const Test &t, int (Test::*f)() const, int x, int y); 

In the target.cpp source file target.cpp I define the function in such a way that

 #include "common.h" void func(const Test &t, int (Test::*f)() const, int x, int y) { std::cout << "f: " << (t.*f)() << ", x: " << x << ", y: " << y << std::endl; } 

In my main file, I define the Test class and use the func function:

 class Test { public: int example() const { return 1; } }; #include "common.h" int main() { Test t; func(t, &Test::example, 0xaaaaaaaa, 0xbbbbbbbb); return 0; } 

Obviously, this is a little smelly, since pointers to member functions are sometimes more than a simple pointer. But the resulting behavior is a little overwhelming: these parameters 0xaaaaaaaa and 0xbbbbbbbb will not be passed correctly to the function. More precisely, the func function interprets the given stack differently than the data is pushed onto the stack by the caller. The size of f depends on whether the class is only declared or actually defined. Result compiled with Visual Studio 2013:

 f: 1, x: 0, y: 2130567168 

I thought that if the shipment declaration is enough, it really doesn't matter if this definition is there or not.

+6
source share
1 answer

By default, MSVC maintains speed over correctness with member pointers. You can make it work according to the standard by passing the /vmg compiler flag.

+4
source

All Articles