In my .h file:
extern std::vector<bool*> selectedContainer;
inline void InitSprite(Sprite* sprite)
{
bool* selected = new bool(false);
sprite->onMouseHover = [&](){
*selected = true;
};
sprite->onMouseNotHover = [&](){
*selected = false;
};
selectedContainer.push_back(selected);
}
If for example the onMouseHover of the passed sprite gets called. The selected pointer is always 0xFFFFFFFF.
CodePudding user response:
[&](){
The &
means that the lambda captures its object by reference.
bool* selected = new bool(false);
This declares selected
in automatic scope. This means that when this function returns selected
goes out of scope and gets destroyed. Note that this means that the pointer itself is destroyed, and that has nothing to do, whatsoever, with whatever the pointer is pointing to.
This pointer is captured by reference, so after this function returns any time the lambda referenced the captured object it will end up referencing a destroyed object, hence the undefined behavior.
The simplest solution is to have the lambdas capture objects by value (by default):
[=](){