首先,請原諒,如果這看起來很明顯 - 我對C++很陌生。我一直在尋找這個,但我沒有發現任何特別有用的東西。EXC_BAD_ACCESS with lambda capture
當試圖訪問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();