#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?
Is
collguaranteed to be valid before exiting this function?collto the constructor of astd::threadinmainfunction, becausecollis an object, it isdecaycopied. Thisdecaycopy essentiallymoves the vector (so it becomes rvalue), which will bind to thecollparameter infduring the execution of the thread. (Thanks for the comment by @Praetorian)Is it safe to pass arguments by reference into a
std::threadfunction?decaycopied, so you actually never pass anything by reference tostd::thread.Reference for
std::decay: http://www.cplusplus.com/reference/type_traits/decay/std::thread