参数的混合值,当我调用指针成员函数时



我已经从另一个类调用了成员函数的指针。此函数有 2 个参数。 它正在工作...但是在这个成员函数中,在调试器中,我看到参数的值被交换(混合)。我看到了正确的值,但没有在正确的变量(参数)中。可能是错误... Qt Creator c++

void SmartCTL::OnReadBufferA(int shm_id, int length); //declaration
hookedIDs[HOOKIDPOINTERS::READBUFFERA] = (void *)&SmartCTL::OnReadBufferA; // Save pointer of function
memcpy(hookedIDs[smartCTL.shellID],smartCTL.hookedIDs,8*sizeof(void *));// copy pointers
void (*pf)(int,int )= (void(*)( int,int ))hookedIDs[i][HOOKIDPOINTERS::READBUFFERA];// set pointer 
pf(shells[i]->readBuff.shm_id,shells[i]->readBuff.length); // call hear

结果我得到值地狱[i]->readBuff.shm_id长度和值shell[i]->readBuff.lengthshm_id

这不是一个错误。 你所拥有的是未定义的是行为。 成员函数与常规函数不同。 成员函数中有一个this,它获取它的方式是通过类类型的隐式函数参数。 所以

void SmartCTL::OnReadBufferA(int shm_id, int length)

真的是这样的

void SmartCTL::OnReadBufferA(SmartCTL& this_ref, int shm_id, int length)

这就是为什么你不能将指向成员函数的指针强制转换为指向常规函数的指针的原因。

如果您需要在"数组"中同时包含成员函数和常规函数,那么您将需要std::function。 它使用类型擦除来允许您存储具有相同接口的不同类型的函数对象。 例如,你可以有类似的东西

std::vector<std::function<void(int, int)>> functions;
functions.push_back(some_regular_function);
functions.push_back([](int shm_id, int length){ SmartCTL s; return s(shm_id, length); });

另一种选择是使成员函数成为静态函数。 静态函数没有绑定到它的类的实例,因此您可以将其视为常规函数。

最新更新