简体   繁体   English

为什么这个地址是 0xFFFFFFFF?

[英]Why is this address 0xFFFFFFFF?

In my .h file:在我的 .h 文件中:

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.例如,如果传递的精灵的onMouseHover被调用。 The selected pointer is always 0xFFFFFFFF.所选指针始终为 0xFFFFFFFF。

[&](){

The & means that the lambda captures its object by reference . &表示 lambda 通过引用捕获其对象。

bool* selected = new bool(false);

This declares selected in automatic scope.这声明在自动范围内selected This means that when this function returns selected goes out of scope and gets destroyed.这意味着当这个函数返回selected会超出范围并被销毁。 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.这个指针是通过引用捕获的,所以在这个函数返回之后,每当 lambda 引用捕获的对象时,它将最终引用一个被销毁的对象,因此是未定义的行为。

The simplest solution is to have the lambdas capture objects by value (by default):最简单的解决方案是让 lambdas 按捕获对象(默认情况下):

[=](){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM