Function local static function-object that's i

2019-04-29 03:40发布

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.

1条回答
Viruses.
2楼-- · 2019-04-29 04:28

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.

查看更多
登录 后发表回答