[英]c++ shared_ptr from char* to void*
I am trying to pass a char *
string to a function which will execute inside a thread. 我试图将
char *
字符串传递给将在线程内执行的函数。 The function has the following prototype: 该函数具有以下原型:
void f(void *ptr);
The thread allocation is made by a function similar to the following: 线程分配由类似于以下的函数进行:
void append_task(std::function<void(void *)> &f, void *data);
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));
I would like to discard the obligation to allocate and deallocate memory manually . 我想放弃手动分配和释放内存的义务。 How can I do this with
std::shared_ptr
(namely, the cast to void, and do I guarantee that the string is deallocated when the thread ends?) 我怎么能用
std::shared_ptr
做这个(即,转换为void,并且我保证在线程结束时取消分配字符串吗?)
PS Changing the append_task()
function IS an option. PS更改
append_task()
函数是一个选项。
First, ditch the second argument to append_task
, and make it take a function with no arguments. 首先,抛弃
append_task
的第二个参数,并使其成为一个没有参数的函数。 Then pass the function
by value, not reference. 然后按值传递
function
,而不是参考。 That way, you can just bind the extra data within a lambda, and count on std::string
and std::function
to do the memory management. 这样,你可以在lambda中绑定额外的数据,并依靠
std::string
和std::function
来进行内存管理。
Like so: 像这样:
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());} );
}
Firstly there is a dangerous bug in your code: 首先,代码中存在一个危险的错误:
char *str = new char[name.length()];
strcpy(str, name.c_str());
std::string::length
returns the size of the string in bytes excluding the null byte at the end of the string . std::string::length
返回std::string::length
的大小,以字节为单位, 不包括字符串末尾的空字节 。 Then you copy into this buffer with strcpy
which reads from a const char *
until it hits a null byte into your buffer which is now too short to contain the null byte. 然后使用
strcpy
复制到此缓冲区, strcpy
从const char *
读取,直到它到达缓冲区的空字节,现在它太短而不能包含空字节。 You then pass this const char *
into a function which now has no idea how long this array is and is probably assuming it to be a null terminated array. 然后你将这个
const char *
传递给一个函数,该函数现在不知道这个数组有多长,并且可能假设它是一个空终止的数组。 This kind of mistake is so common in C that you really need to avoid directly handling C-style strings as much as humanly possible. 这种错误在C中很常见,你真的需要避免直接处理C风格的字符串尽可能多的人。
As to how to solve your problem I can't improve on the solution using lambdas that Sneftel provides. 至于如何解决您的问题,我无法改进使用Sneftel提供的lambda的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.