【发布时间】:2016-08-20 21:22:44
【问题描述】:
首先,如果这看起来很明显,请原谅 - 我对 C++ 有点陌生。我一直在研究这个,但我没有发现任何特别有用的东西。
当尝试访问 lambda 中捕获的变量时,我的应用程序崩溃了,我不知道为什么。我不认为该对象已被删除,因为在它崩溃的地方放置一个断点并使用 CLion 的调试器时,CLion 显示该对象存在。
一个代码示例可能会帮助我解释这一点:
//Create the progress dialog
QProgressDialog *progDialog = new QProgressDialog(tr("Opening Project…\nExtracted: 0 (0.0%)\nWaiting…"), nullptr, 0, 0, this);
// ... Some code here
//Declare a function to be passed as a callback
std::function<void (int minValue, int maxValue)> *progRangeChangedCallback = nullptr;
// ... More code here
//Create the lambda
//I capture progDialog (The progress dialog)
auto progRangeChangedCallbackLambda = [&progDialog](int newMin, int newMax) {
//Putting a breakpoint here reveals that progDialog exists
//CLion even autocompletes the below functions
//when trying to evaluate an expresion
progDialog->setMinimum(newMin); //EXC_BAD_ACCESS: Crashes happen here!
progDialog->setMaximum(newMax);
};
// ... Even more code here
//Put the lambda in a std::function
progRangeChangedCallback = new std::function<void (int minValue, int maxValue)>(progRangeChangedCallbackLambda);
// ... More code
//Pass the std::function object as a callback to a new thread
//This extends QThread
OpenProjectThread *thread = new OpenProjectThread(filePath, this, progChangedCallback, progRangeChangedCallback, onSuccessCallback, onErrorCallback);
thread->start();
【问题讨论】:
标签: c++ c++11 exception lambda