nr: #2 dodano: 2017-01-05 07:01
As @T.C.'s comment, you're not passing reference to thread, you just make a copy of the vector in the thread:
thread(f, coll).detach(); // It's NOT pass by reference, but makes a copy.
If you really want to pass by reference, you should write this:
thread(f, std::ref(coll)).detach(); // Use std::ref to pass by reference
Then the code will get segment fault if the thread tries to access the vector, since when the thread runs, it's very likely the vector is destructed.
So to your question:
Is it safe to pass arguments by reference into a std::thread function?
- It is safe if you're sure the object remains valid during the thread's running;
- It is NOT safe if the object is destructed, and you will get segment fault.