【问题标题】:static definition of a lambda in std::vector crashes in multi-threaded environmentstd::vector 中 lambda 的静态定义在多线程环境中崩溃
【发布时间】:2015-03-23 11:26:39
【问题描述】:

这是类中方法的代码 sn-p:

....
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&lt;InterfaceOptionsResolve&gt; vKeywords = 的定义更改为static std::vector.... 时,应用程序在多线程环境中崩溃得可怕(分段错误)。我不明白为什么。对我来说,只有 lambda 代码和 const std::stringstatic,但通过 [&amp;] 访问方法变量应该在活动范围内完成。

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

这里是InterfaceOptionsResolve的定义:

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

【问题讨论】:

  • 每个关键字的 lambda 都是相同的,那么为什么要使用相同的代码生成不同类型的负载,而不是仅使用命名函数呢?!
  • @JonathanWakely:不,当然不是!这只是一个sn-p!每个关键字都有完全不同的代码!
  • 啊好吧,我误会了。这不会改变我在下面的答案(这就是为什么我把这个不相关的评论作为评论)

标签: multithreading c++11 vector lambda static


【解决方案1】:

对我来说,只有 lambda 代码和 const std::string 是静态的,但通过 [&amp;] 访问方法变量应该在活动范围内完成。

不,lambda 表达式在静态向量第一次初始化时运行,因此[&amp;] 捕获将绑定到 current 范围内的sHelper 的引用。下次运行该函数时,sHelper 消失了,并且在范围内有一个完全不同的对象 sHelper,但您的静态 lambdas 仍然引用旧的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多