Consider the case below
The name string is moved as an argument to the stream.
void start(std::string&& name) { t = std::thread{&ThreadRunner::run, this, std::forward<std::string>(name)}; }
The thread execution function also accepts an rvalue reference.
void run(std::string&& name) { const auto errnum = pthread_setname_np(t.native_handle(), name.c_str()); if (errnum != 0) { std::cout << "ERROR " << std::endl; } }
A stream is created using the start function, as shown below:
ThreadRunner r; r.start(std::string("somename"));
Question. Is it possible that std :: string, accessible in the run function via pthread_setname_np, might be undesirable since a temporary value goes out of scope when the scope completes?
Demo In the above demonstration after the call completed, is it confirmed that the string somename valid in the run function?
Edit: The demo with the std :: string constructors / destructors in the question is now replaced with Wrap to print the involved constructors.
Result: (the second field is the address of the object, the third is the identifier of the stream)
Constructed 0x7ffc395e0ef0 140605000369984 Move Constructed 0x7ffc395e0e60 140605000369984 Move Constructed 0x177a0a0 140605000369984 Destroyed 0x7ffc395e0e60 140605000369984 Destroyed 0x7ffc395e0ef0 140605000369984 Call ended somename Destroyed 0x177a0a0 140604983461632
The last object is destroyed after run completed. It is still temporary. I think no.
Cleaner example
Edit: After commenting, the question comes down to
"After the initial call to the empty start (std :: string && name); returns even after the constructor std :: thread is completed, where is the line that starts void (std :: string && name); works?"
The last demo code seems to show that the Wrap object referenced by run is destroyed after run exits.
c ++ multithreading c ++ 11 move stdthread
themagicalyang
source share