[英]Program crashed with “bad_function_call” when a lambda's struct/class member is called
我想测试哪种方法更快地清理std::deque
使用std::deque::cleaner
, std::deque::swap
和std::deque::pop_back
。
为此,我创建了一个具有以下内容的程序:
Testit
并使用特定方法接收lambda的功能; 当我运行程序时,我得到了“ bad_function_call ”。
该程序出了什么问题?如何解决该问题,以使lambdas成员可以正常使用struct / class?
在下面,您可以看到该程序的重要部分:
//Procedure to test. It receive a lambda with the method to clean the deque up.
int Testit(auto& fCleanUp_the_Container) {
(...)
deque<string> vdTEST; //deque to be tested
//Add elements to vdTEST
fCleanUp_the_Container(vdTEST);
(...)
}
struct dData {
//The Description and lMethodtoCleanUp will be initialize with the std::vector::emplace_back method.
dData(string Description, function<void(deque<string>& vdTEST)> lMethodtoCleanUp) {};
int Results = 0;
string Description;
function<void(deque<string>& vdTEST)> lMethodtoCleanUp;
};
int main () {
(...)
//upload the data to a vector;
vector<dData> dDt;
dDt.emplace_back("clear", [](deque<string>& vdTEST) {vdTEST.clear();}); //Using std::deque::clear
dDt.emplace_back("swap", [](deque<string>& vdTEST){deque<string> vdTMP; vdTEST.swap(vdTMP);}); //Using std::deque::swap
dDt.emplace_back("pop_back", [](deque<string>& vdTEST){while (!vdTEST.empty()) vdTEST.pop_back();}); //Using std::deque::pop_back
//running the test
for (int iIta=1; iIta != noofCycles; iIta++) {
cout << "\nCycle " << iIta << "...";
for (auto& iIt : dDt) //Test all members of dDt
iIt.Results += Testit(iIt.lMethodtoCleanUp);
}
(...)
}
您的构造函数
dData(string Description, function<void(deque<string>& vdTEST)> lMethodtoCleanUp) {};
忽略其参数Description
和lMethodtoCleanUp
。 它不会初始化也恰巧名为Description
和lMethodtoCleanUp
类成员。
您应该做两件事:
正确的构造函数实现为:
dData(string Description, function<void(deque<string>& vdTEST)> lMethodtoCleanUp)
: Description(Description), lMethodtoCleanUp(lMethodtoCleanUp) {};
注意,在例如Description(Description)
的两次出现Description
指的是两个不同的变量:类成员和构造参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.