首页 > 解决方案 > 当我调用指针成员函数时,参数的混合值

问题描述

我从另一个类中调用了成员函数的指针。该函数有 2 个参数。它正在工作......但是在这个成员函数中,在调试器中,我看到参数的值被交换(混合)。我看到了正确的值,但没有看到正确的变量(参数)。可能是BUG... 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

结果我得到了长度值 hells [ i]->readBuff.shm_id和shm_idshells[i]->readBuff.length

标签: c++functionpointersqt-creator

解决方案


这不是错误。你所拥有的是未定义的行为。成员函数与常规函数不同。成员函数中有一个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); });

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


推荐阅读