Ahmad Siavashi Ahmad Siavashi - 2 months ago 14x
C++ Question

Thread-safety of using unique_ptr inside lambda when creating new thread

I would like to know if the following code is thread-safe

void use_value(int i, unique_ptr<vector<int>> v);
for (int i = 0; i < 10; i++){
unique_ptr<vector<int>> ptr = make_unique<vector<int>>(10);
// ...
// Here, the vector pointed to by ptr will be filled with specific values for each thread.
// ....
[i, &ptr](){
use_value(i, move(ptr));

Thank you


It's undefined behavior. You don't know when the lambda body will be called. So that ptr you capture by reference can very well be out of scope by then, the resource destructed, and you are left with a dangling reference.

You should "move-capture" the ptr (or better yet, just the vector) into the lambda, if you have access to c++14.

If you move (or copy) the vector, your code will be thread safe.