#include <thread>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
void f(const vector<string>& coll)
{
this_thread::sleep_for(1h);
//
// Is coll guaranteed to be valid before exiting this function?
//
}
int main()
{
{
vector<string> coll(1024 * 1024 * 100);
thread(f, coll).detach();
}
//
// I know std::thread will copy arguments into itself by default,
// but I don't know whether these copied objects are still valid
// after the std::thread object has been destroyed.
//
while (true);
}
Is it safe to pass arguments by reference into a std::thread function?
As @T.C.'s comment, you're not passing reference to thread, you just make a copy of the vector in the thread:
If you really want to pass by reference, you should write this:
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: