#include <iostream>
#include <functional>
#include <memory>
#include <string>
using namespace std;
struct library
{
library( )
{
cout << "creating library\n " ;
}
~library( )
{
cout << "destroying library\n " ;
}
} ;
template < typename Signature>
class library_function
{
public :
library_function(
shared_ptr< library> lib, Signature* library_function)
:
m_library( lib) ,
m_function( library_function)
{ }
operator Signature* ( ) const { return m_function; }
private :
shared_ptr< library> m_library;
Signature* m_function;
} ;
void test_lib_func( string s)
{
cout << "called test_lib_func(" << s << ")\n " ;
}
int main( )
{
shared_ptr< library> lib = make_shared< library> ( ) ;
{
library_function< void ( string) > functor( lib, test_lib_func) ;
functor( "direct call before reset" ) ;
lib.reset ( ) ;
functor( "direct call after reset" ) ;
cout << "functor about to go out of scope\n " ;
}
lib = make_shared< library> ( ) ;
function< void ( string) > func =
library_function< void ( string) > ( lib, test_lib_func) ;
func( "std::function call before reset" ) ;
lib.reset ( ) ;
func( "std::function call after reset" ) ;
return 0 ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8ZnVuY3Rpb25hbD4KI2luY2x1ZGUgPG1lbW9yeT4KI2luY2x1ZGUgPHN0cmluZz4KCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpzdHJ1Y3QgbGlicmFyeQp7CglsaWJyYXJ5KCkKCXsKCQljb3V0IDw8ICJjcmVhdGluZyBsaWJyYXJ5XG4iOwoJfQoJfmxpYnJhcnkoKQoJewoJCWNvdXQgPDwgImRlc3Ryb3lpbmcgbGlicmFyeVxuIjsKCX0KfTsKCnRlbXBsYXRlPHR5cGVuYW1lIFNpZ25hdHVyZT4KY2xhc3MgbGlicmFyeV9mdW5jdGlvbgp7CnB1YmxpYzoKICAgIGxpYnJhcnlfZnVuY3Rpb24oCiAgICAgICAgc2hhcmVkX3B0cjxsaWJyYXJ5PiBsaWIsIFNpZ25hdHVyZSogbGlicmFyeV9mdW5jdGlvbikKICAgICAgICA6CiAgICBtX2xpYnJhcnkobGliKSwKICAgIG1fZnVuY3Rpb24obGlicmFye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