调用 lambda 的结构/类成员时程序崩溃并"bad_function_call"

Program crashed with "bad_function_call" when a lambda's struct/class member is called

本文关键字:崩溃 call bad 程序 function lambda 结构 成员 调用      更新时间:2023-10-16

我想测试使用std::deque::cleanerstd::deque::swapstd::deque::pop_back清理std::deque的方法更快。

为此,我创建了一个程序,该程序具有:

  1. 使用特定方法测试Testit并接收 lambda 的函数;
  2. 带有方法描述的结构,带有方法本身和结果的 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) {};

忽略其参数DescriptionlMethodtoCleanUp。它不初始化也恰好被命名为 DescriptionlMethodtoCleanUp 的类成员。

您应该做两件事:

  1. 阅读成员初始化列表(这是许多其他问题中的一个相关SO问题(。
  2. 打开所有编译器警告并将其视为错误。

正确的构造函数实现是:

dData(string Description, function<void(deque<string>& vdTEST)> lMethodtoCleanUp) 
   : Description(Description), lMethodtoCleanUp(lMethodtoCleanUp) {};

例如注释 Description(Description) Description的两次出现是指两个不同的变量:类成员和构造函数参数。