使用std :: bind和boost :: signals2是否安全?

lin*_*s77 6 c++ boost signals bind member-functions

使用std :: bind将成员函数传递给boost :: signals2 :: signal :: connect()是否安全?换句话说,boost :: bind和std :: bind是否可以互换?

它用VC++ 2010 SP1编译,但模板代码远远超过我的头脑,我担心我可能冒险进入未定义的行为领域.

Nic*_*las 1

connect函数采用一个boost::function对象,该对象基本上是任何operator()定义的对象的通用包装器。因此,它与您所绑定的内容一样安全。

例如,这是相当安全的:

boost::shared_ptr<ClassName> pValue = boost::make_shared<ClassName>(...);
signal.connect(boost::bind(&ClassName::FuncName, pValue, ...);
Run Code Online (Sandbox Code Playgroud)

boost::shared_ptr这是相当安全的,因为它将 a作为其数据的一部分存储。

ClassName *pValue = new ClassName(...);
signal.connect(boost::bind(&ClassName::FuncName, pValue, ...);
Run Code Online (Sandbox Code Playgroud)

这是有条件的安全。如果该连接仍然存在并且您执行,它会立即变得不安全delete pValue

就我个人而言,我不太相信“有条件安全”,但这取决于你。关键是,只要你绑定的所有东西还被boost::bind绑定,它就必须继续存在。