Consider the case below
The name string is moved as an argument to the thread.
void start(std::string&& name) {
t = std::thread{&ThreadRunner::run, this, std::forward<std::string>(name)};
}
The thread's run function also takes a 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;
}
}
The thread is created via the start function as below:
ThreadRunner r;
r.start(std::string("somename"));
The question is. Could it be possible that the std::string accessed in the functionrun
via pthread_setname_np can be junk because the temporary went out of scope when it's scope ended?
Demo
In the above demo, after call
ended, is it guranteed that the somename
string is valid in the function run
?
Edit:
Demo with constructors/destructors
The std::string in the question is now replaced with a Wrap
to print the constructors involved.
The result is: (second field is the address of the object, third is the thread id)
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
ends. Does it still refer to a temporary. I think not.
A more clean example
Edit: After the comments, the question boils down to
"After the original call to void start(std::string&& name); has returned and after the constructor of std::thread has ended, where is the string that void run(std::string&& name); is working on? "
The latest demo code seems to show that the object Wrap
being referenced by run
gets destroyed after run
exits.
Details in the process of constructing a std::thread object
The accepted answer in the above post clarifies the situation here.
The function run
takes a reference to a temporary which is destroyed after the completion of the run
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With