【发布时间】:2017-05-19 12:23:03
【问题描述】:
#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);
}
通过引用将参数传递给 std::thread 函数是否安全?
【问题讨论】:
-
简短回答:是的,完全安全且没问题。
-
你没有通过对线程的引用传递任何东西。
-
我很抱歉,你是对的;我看错了代码。
-
@TC,我知道
std::thread默认会将参数复制到自己中,但我不知道这些复制的对象在std::thread对象被销毁后是否仍然有效。 -
std::thread对象不再与执行线程相关联,因为您来自它的detach。thread本身会在调用f时移动vector,这将绑定到vector const&参数,并且它的生命周期将在f退出时结束,因此您的代码是安全的。
标签: c++ multithreading c++11 standards object-lifetime