C ++ std :: bind使对象保持活动状态 [英] c++ std::bind keeping object alive

查看:56
本文介绍了C ++ std :: bind使对象保持活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码,非常简单.

class Foo
{
public:
    void print()
    {
        std::cout<<"Foo::print\n";
    }
}; 


Game::Game()
{
    {
        Foo foo;
        player.onclick = bind(&Foo::print,foo);

    }
    player.onclick();
}

在完成内部作用域之后,foo对象超出了作用域,但仍调用了print方法,我猜发生这种情况是因为播放器拥有对foo对象的引用?有没有办法阻止这种情况的发生?我不希望对象存活并在应该销毁事件时接收事件.

After the inner scope is done the foo object goes out of scope, but the print method is still called, I guess this happens because player holds a reference to the foo object? Is there a way to stop this from happening? I don't want objects to stay alive and receive events when they are supposed to be destroyed.

谢谢.

推荐答案

您正在绑定到 foo 的副本;该副本的持续时间与绑定的函数对象一样长,而原始的 foo 在其作用域的结尾处被破坏.

You are binding to a copy of foo; that copy lasts as long as the bound function object, while the original foo is destroyed at the end of its scope.

如果不想让它保持活动状态,请绑定到指针(& foo )或引用( std :: ref(foo));然后必须小心,一旦 foo 超出范围,就不要调用函数对象.注意,没有办法从函数对象中得知发生了这种情况.调用它会产生不确定的行为.

If you don't want to keep it alive, then bind to a pointer (&foo) or a reference (std::ref(foo)); and then you must be careful not to call the function object once foo has gone out of scope. Note that there's no way to tell from the function object that this has happened; calling it will give undefined behaviour.

为了在对象被销毁时安全断开连接,您必须安排其析构函数重新分配 onclick ,或者让其他对象负责首先重新分配 onclick ,然后销毁对象.

In order to safely disconnect the object when it's destroyed, you would have to either arrange for its destructor to reassign onclick, or make some other object responsible for first reassigning onclick, and then destroying the object.

这篇关于C ++ std :: bind使对象保持活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆