Is the following function thread-safe? And if it's not thread-safe, then is there really any overhead in making that funImpl non-static? Or does the compiler actually inline that function-object function and skip creating the function object altogether?
int myfun(std::array<int, 10> values)
{
static const auto funImpl = [&]() -> int
{
int sum = 0;
for (int i = 0; i < 10; ++i)
{
sum += values[i];
}
return sum;
};
return funImpl();
}
EDIT: I edited the function signature from:
int myfun(const std::array<int, 10>& values)
to:
int myfun(std::array<int, 10> values)
so that it is clear that I'm not asking about the tread-safety of values, but the thread-safety of the function local static variable funImpl.
No, static functions are not inherently thread-safe.
There are three ways in C++ to initialize variables in a thread safe way.
Not only is it not thread safe, it doesn't do what you want.
By defining the lambda as static, it captures (by reference) the array passed in the first time it's called. Further calls continue to reference the original array, regardless of which array is passed in.
When the first array goes out of scope, further calls will invoke UB, as it now has a dangling reference.
Edit: An example http://ideone.com/KCcav
Note, even if you captured by value, you'd still have a problem because it would still only capture the first time you invoke the function. You wouldn't have the dangling pointer, but it still would only initialize the copy the first time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With