Access to moved std :: string in a new thread

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.

+7
c ++ multithreading c ++ 11 move stdthread
source share
2 answers

Details in the process of creating an std :: thread object

The accepted answer in the above message clarifies the situation here. The run function accepts a temporary reference, which is destroyed after the run function completes.

+1
source share

There is no reference to dangling , since the arguments to the std::thread constructor are copied / moved to some structure on the client thread. Then the created thread will be launched on copied / moved objects in this structure.

In your particular case, the std::string object really moves into the described structure. That the std::string run() object works. It will be correctly destroyed when the thread completes execution.

0
source share

All Articles