Is this safe to capture a temporary variable in a thread function?
std::vector<std::string> adapterList = getAdapterList();
std::vector<std::thread> captureThreads;
for (auto adapterName : adapterList) {
captureThreads.push_back(std::thread([&] {
// do something with adapterName. Safe?
}));
}
for (auto& thread : captureThreads) {
if (thread.joinable())
thread.join();
}
3
Definitely not, in this case. You are capturing by reference, while your adapterName
is a copy, so it’s going away after each loop iteration.
Make the adapterName
a reference and you should be fine, since your adapterList
remains alive and unchanged while your threads are running.
Note: in C++, a “reference to a reference” doesn’t exist, so capturing a reference by reference will just be a reference to the same object. Can you make a sentence with more instances of the word “reference”?