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

让人想犯罪 __ 提交于 2019-12-22 05:42:27

问题


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:


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.



来源:https://stackoverflow.com/questions/11619201/function-local-static-function-object-thats-initialized-by-lambda-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!