我正在使用AUI Framework,它具有与Qt类似的信号槽系统。我想访问接收者对象的状态。我尝试用 C++ lambda 捕获接收者对象:
auto model = _new<ATreeModel<AString>>(...);
_new<ATreeView>(model).connect(&ATreeView::itemSelected, model, [this, &model](ATreeModelIndex index){
auto selected = model->itemAt(index);
// ...
});
但我有
[UI thread][SignalHandler][ERR]: Caught signal: Segmentation fault(11).
为什么?
那是因为您通过引用捕获了
model
。目前 lambda 被调用(在您的情况下,当用户选择树视图项时)model
超出了范围,因此对它的引用是一个悬空指针。
model
变量是共享指针,因此无需通过引用将其存储在 lambda 中。只需按值存储即可:[this, model]
。
正如您提到的Qt,存在完全相同的问题:https://forum.qt.io/topic/122849/connect-with-lambda-and-capture-by-reference-causes-segmentation-fault/2