std::vector 中 lambda 的静态定义在多线程环境中崩溃

static definition of a lambda in std::vector crashes in multi-threaded environment

这是 class 中方法的代码片段:

....
std::string sHelper (sKey);

// interface keys definition with corresponding code implemented as lambda
std::vector<InterfaceOptionsResolve> vKeywords =
{
    {
        "{Instrument}",
        [&] (const std::string sKeyword)
        {
            // sInstrument is a member in the class
            sHelper.replace(sHelper.find(sKeyword), sKeyword.size(), sInstrument);
        }
    },
    ....
};

// check each interface template keyword against the provided interface template name
for ( const auto &itKeyword : vKeywords )
{
    if ( strstr(sHelper.c_str(), itKeyword.sParameter.c_str()) )
    {
        // if the interface key was found replace it with the corresponding value
        itKeyword.oLambda(itKeyword.sParameter);
    }
}
....

简而言之:在方法函数中,我定义了一个带有关键字的 std::vector 和一个为每个匹配的关键字执行的 lambda 函数。我本可以做几个 if !strcmp(....) { the code from the lambda function } 但我更喜欢这样。

当我将 std::vector<InterfaceOptionsResolve> vKeywords = 的定义更改为 static std::vector.... 时,应用程序会在多线程环境中严重崩溃(分段错误)。我不明白为什么。对我来说,只有 lambda 代码和 const std::stringstatic,但是通过 [&] 访问方法变量应该从活动范围完成。

谁能解释一下我哪里有逻辑错误?

这里是InterfaceOptionsResolve的定义:

typedef struct
{
    const std::string       sParameter;
    std::function<void(const std::string)>  oLambda;
} InterfaceOptionsResolve;

For me only the lambda code and const std::string are static but the access to the method variables via [&] should be done from the active scope.

不是,lambda表达式运行s是在静态vector第一次初始化的时候,所以[&]捕获会在中绑定对sHelper的引用当前 范围。当你下一个 运行 函数时,那个 sHelper 消失了,并且在范围内有一个完全不同的对象 sHelper ,但是你的静态 lambda 仍然引用旧的。