#include
#include
#include
#include
using namespace std;
void f(const vector& coll)
{
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 already destructed (because it went out of it's scope in the main program).
So to your question:
Is it safe to pass arguments by reference into a
std::thread
function?
Is coll
guaranteed to be valid before exiting this function?
coll
to the constructor of a std::thread
in main
function, because coll
is an object, it is decay
copied. This decay
copy essentially move
s the vector (so it becomes rvalue), which will bind to the coll
parameter in f
during the execution of the thread. (Thanks for the comment by @Praetorian)Is it safe to pass arguments by reference into a std::thread
function?
decay
copied, so you actually never pass anything by reference to std::thread
.Reference for std::decay
: http://www.cplusplus.com/reference/type_traits/decay/
std::thread