man*_*tta 4 c++ multithreading
I am trying to pass a char * string to a function which will execute inside a thread. The function has the following prototype:
void f(void *ptr);
Run Code Online (Sandbox Code Playgroud)
The thread allocation is made by a function similar to the following:
void append_task(std::function<void(void *)> &f, void *data);
Run Code Online (Sandbox Code Playgroud)
I want to allocate a string that will be used inside the thread. Right Now I have this:
string name = "random string";
char *str = new char[name.length()];
strcpy(str, name.c_str());
append_task(f, static_cast<void *>(str));
Run Code Online (Sandbox Code Playgroud)
我想放弃手动分配和释放内存的义务.我怎么能这样做std::shared_ptr(即,转换为void,并且我保证在线程结束时取消分配字符串?)
PS更改append_task()功能是一个选项.
首先,抛弃第二个参数append_task,并使其成为一个没有参数的函数.然后传递functionby值,而不是引用.这样,您就可以在lambda中绑定额外的数据,并依靠std::string并std::function进行内存管理.
像这样:
void f(void *ptr);
void append_task(std::function<void()> f);
int main()
{
std::string name = "random string";
append_task( [=]{f((void*)name.c_str());} );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
447 次 |
| 最近记录: |