C ++ shared_ptr from char * to void *

I am trying to pass a string to a char *function that will be executed inside a thread. The function has the following prototype:

void f(void *ptr);

Thread allocation is performed using a function similar to the following:

void append_task(std::function<void(void *)> &f, void *data);

I want to highlight the string that will be used inside the stream. 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 abandon the obligation to allocate and free up memory manually. How can I do this with std::shared_ptr(namely, for casting into the void and do I guarantee the release of the string when the stream ends?)

PS Function change append_task()is an option.

+4
source share
2 answers

append_task . function , . , 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());} );
}
+6

-, :

char *str = new char[name.length()];
strcpy(str, name.c_str());

std::string::length , . strcpy, const char *, , , . const char * , , , , , . C, C-, -.

, , lambdas, Sneftel.

+4

All Articles