template< typename _Func >
class auto_call_func_t : public noncopyable_t
{
public:
auto_call_func_t( std::function< _Func > f ) : func( f ), will_call( true ){}
~auto_call_func_t( void ) noexcept
{
if ( will_call )
{
try { ( void )func(); }
catch ( ... ) {}
}
}
/* This helps prevent some "unused variable" warnings under, for instance,
* GCC 3.2.
*/
void touch( void )const {}
void cancel_call( void ) noexcept { will_call = false; }
private:
std::function< _Func > func;
bool will_call;
};
例子:
auto_call_func_t < void( void ) > auto_free( [this]( void ){ this->ui->toolButton->setEnabled(true); } );
例如当代码执行结束后或者return了,都要把button重新设置成可用,只要在代码开始时加入这一行代码,结束后会自动执行,像析构函数一样