【发布时间】:2014-07-14 18:27:03
【问题描述】:
我有一个类foo,它接受一个指向类bar的方法之一的成员函数指针,但是类bar的生命周期可能比foo短执行前是否存在?
目前,我正在尝试使用std::function 的bool operator,但没有成功。
class Foo
{
public:
void Foo::SetCallback( std::function< void( void ) > cb )
{
_cb = cb; // My Bar class will call this to assign a Bar member function pointer to Foo's _cb member variable
}
void Foo::CallCallback()
{
if( _cb ) _cb(); // This evaluates to true even if the original bar object has been destroyed
//I want this callback to only execute if the bar object exists
}
private:
std::function< void( void ) > _cb;
};
class Bar
{
public:
Bar( Foo* _foo )
{
_foo->SetCallback( std::bind( &myCalledbackFunc, this );
}
void myCalledbackFunc()
{
//do stuff
}
};
【问题讨论】:
-
抱歉,您的问题我完全不清楚。
bar到底是什么?请输入一个minimal sample,以重现您实际遇到的行为和错误。 -
除了仿函数之外还有一个 bar 实例的 weak_ptr 作为函数参数怎么样?
-
@SilvesterSeredi 听起来是个好主意...我不熟悉
std::weak_ptr虽然我可以简单地在我的Barctor 中从this创建一个吗? -
您可以在 foo 中拥有
register_callback和deregister_callback函数,并在bar类的析构函数中取消注册回调。 -
@perreal 这是我现有的临时解决方案......我只是希望 Functor 可以用来识别它引用的成员的类的存在。
标签: c++ functor member-function-pointers