c++ shared_ptr from char*to void*

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()功能是一个选项.

Sne*_*tel 6

首先,抛弃第二个参数append_task,并使其成为一个没有参数的函数.然后传递functionby值,而不是引用.这样,您就可以在lambda中绑定额外的数据,并依靠std::stringstd::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)

  • @AaronMcDaid不,它没有.因为lambda捕获是按值(由于`[=]`)而不是引用,所以字符串的单独副本存储在closure-type中(因此在`function`中).lambda中的变量称为"name",但它是一个*不同的*"name". (2认同)