c++ - 当我调用指针成员函数时,参数的混合值
问题描述
我从另一个类中调用了成员函数的指针。该函数有 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_id值shells[i]->readBuff.length
解决方案
这不是错误。你所拥有的是未定义的行为。成员函数与常规函数不同。成员函数中有一个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); });
另一种选择是使成员函数成为静态函数。静态函数没有绑定到它的类的实例,因此您可以将其视为常规函数。
推荐阅读
- java - java中的方法 DateTime.now() 和 new DateTime(System.currentTimeMillis()) 是否相等?
- selenium - webdriver接口和chromedriver类之间的远程webdriver的目的是什么
- android - MS TTS 认知服务 URL 的 traiffiqtype 参数的用途是什么
- python - 初始化一对变量 - 1 是什么意思?
- html - 处理同一表单上的多个提交按钮
- .net - 无法加载共享库“db2app64.dll”
- mysql - 选择排除同一列中mysql查询中特定值的字段
- r - 如何一次性汇总几年数据的天数?
- php - 始终在 WooCommerce 电子邮件通知中显示送货地址
- django - 'NoneType' 类型的参数对于 django 字符串“”是不可迭代的