When I was working on a problem today, the void * type was used, so record it here
A rough description of the problem: how to use a function with void * type as a parameter
void Problem(void* user_data);
The following is an example of passing a shared pointer: the code is very simple, read it patiently.
Pay attention to two points: two long comments in the following code
#include <iostream>
using namespace std;
class StopMyDate {
public:
string aaa;
string bbb;
string ccc;
};
void sss(void* user_data)
{
// 注意该处:类似于 *((int*)user_data) /***************注意1*************/
auto m_user_data = *((shared_ptr<StopMyDate>*)user_data);
string aa = m_user_data->aaa;
cout << "m_user_data->aaa : " << aa.c_str() << endl; //测试是否正确
}
int main()
{
shared_ptr<StopMyDate>stopMyDate(new StopMyDate); // 定义一个共享指针,类型stopMyDate
// 给成员赋值
stopMyDate->aaa = "aaaaa";
stopMyDate->bbb = "bbbbb";
stopMyDate->ccc = "ccccc";
// 此处调用,需注意添加(void*) /***************注意2*************/
sss((void *)&stopMyDate);
return 0;
}
Output:
m_user_data->aaa : aaaaa
End:
Sharing is also a way to deepen your understanding of the problem again. It may not be comprehensive, but it is definitely useful and will continue to be improved later~