调用 lambda 的结构/类成员时程序崩溃并"bad_function_call"
Program crashed with "bad_function_call" when a lambda's struct/class member is called
我想测试使用std::deque::cleaner
、std::deque::swap
和std::deque::pop_back
清理std::deque
的方法更快。
为此,我创建了一个程序,该程序具有:
- 使用特定方法测试
Testit
并接收 lambda 的函数; - 带有方法描述的结构,带有方法本身和结果的 lambda;
当我运行该程序时,我得到了">bad_function_call"。
该程序有什么问题,我该如何修复它以使结构/类在 lambda 成员中按预期工作?
您可以在下面看到该程序的重要部分:
//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
的类成员。
您应该做两件事:
- 阅读成员初始化列表(这是许多其他问题中的一个相关SO问题(。
- 打开所有编译器警告并将其视为错误。
正确的构造函数实现是:
dData(string Description, function<void(deque<string>& vdTEST)> lMethodtoCleanUp)
: Description(Description), lMethodtoCleanUp(lMethodtoCleanUp) {};
例如注释 Description(Description)
Description
的两次出现是指两个不同的变量:类成员和构造函数参数。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我的多线程作业队列崩溃
- ExtractIconEx:可以工作,但偶尔会崩溃
- 为什么引用传递会导致此崩溃(C++)
- 试图创建流或fopen时程序崩溃
- 类对象数组的问题会导致崩溃
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 为什么要增加导致崩溃的指针
- 在虚幻引擎中删除NXOpen对象时崩溃
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- Call IConnectionPoint::建议导致崩溃