繁体   English   中英

调用lambda的结构/类成员时,程序因“ bad_function_call”崩溃

[英]Program crashed with “bad_function_call” when a lambda's struct/class member is called

我想测试哪种方法更快地清理std::deque使用std::deque::cleanerstd::deque::swapstd::deque::pop_back

为此,我创建了一个具有以下内容的程序:

  1. 用于测试Testit并使用特定方法接收lambda的功能;
  2. 具有方法说明的结构,具有方法本身和结果的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) {};

忽略其参数DescriptionlMethodtoCleanUp 它不会初始化也恰巧名为DescriptionlMethodtoCleanUp类成员。

您应该做两件事:

  1. 阅读成员初始化列表上的内容是许多其他相关的SO问题)。
  2. 打开所有编译器警告,并将其视为错误。

正确的构造函数实现为:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM