【发布时间】: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<InterfaceOptionsResolve> vKeywords = 的定义更改为static std::vector.... 时,应用程序在多线程环境中崩溃得可怕(分段错误)。我不明白为什么。对我来说,只有 lambda 代码和 const std::string 是 static,但通过 [&] 访问方法变量应该在活动范围内完成。
谁能解释一下我哪里有逻辑错误?
这里是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