我有以下 lambda
direction->addClickEventListener([=](Ref* sender){
std::unordered_map<int,int> data;
rep->getData(DIRECTION, data);
int last = data[1];
int rotation = (last + 45)%360;
LOG("l:%i r:%i",last,rotation);//Always logs l:0 r:45
direction->setRotation(rotation);
data[1] = rotation;
rep->setData(DIRECTION, data);
});
Run Code Online (Sandbox Code Playgroud)
getData 在哪里:
void getData(DATA_KEY key,std::unordered_map<int,int>& data){
//Modifies data with the appropriate values for key, for the current state of rep
}
void setData(DATA_KEY key,std::unordered_map<int,int>& data){
//Makes a copy of data stores it internally with key
}
Run Code Online (Sandbox Code Playgroud)
rep 是指针,所以我认为每当调用 lambda 时,数据的当前值将始终反映 rep 的当前状态。但似乎它始终是调用 direction->addClickEventListener 时任何 rep 的值。
如果我想使用 rep 的当前状态,我该如何修改我的 lambda ?编辑:由于 rep 是一个指针,我不能通过引用捕获..
我不太确定你在问什么,所以这可能不是你问题的答案,但它试图澄清通过引用捕获的问题是什么。
看起来您拥有一个基于事件的系统。了解事件的重要一点是它们可能随时发生。
现在让我们说你有这样的东西(非常简化和伪):
void some_function(some_type* rep)
{
add_event_listener([&]()
{
do_something(rep);
});
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有一个很严重的bug:当事件被调用并且lambda被调用时,函数some_function已经返回,因此局部变量 的作用域rep不再存在。因此,当rep在 lambda 中使用时,它是对不再存在的变量的引用(请记住,这rep是一个局部变量)。这当然会导致未定义的行为。
如果改为按值捕获,则会复制指针,这意味着您现在有两个指针变量,它们都指向同一内存。那么第一个变量是否超出范围并不重要,因为第二个变量仍然有效。