Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function local static function-object that's initialized by lambda, thread-safe or not?

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.

like image 757
zeroes00 Avatar asked Jul 23 '12 19:07

zeroes00


People also ask

Are static function variables thread safe?

No, static functions are not inherently thread-safe.

How many ways are there in C++ for initializing variables in a thread safe way?

There are three ways in C++ to initialize variables in a thread safe way.


1 Answers

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.

like image 50
Dave S Avatar answered Sep 30 '22 13:09

Dave S