fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <memory>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. struct library
  9. {
  10. library()
  11. {
  12. cout << "creating library\n";
  13. }
  14. ~library()
  15. {
  16. cout << "destroying library\n";
  17. }
  18. };
  19.  
  20. template<typename Signature>
  21. class library_function
  22. {
  23. public:
  24. library_function(
  25. shared_ptr<library> lib, Signature* library_function)
  26. :
  27. m_library(lib),
  28. m_function(library_function)
  29. {}
  30.  
  31. operator Signature*() const { return m_function; }
  32.  
  33. private:
  34. shared_ptr<library> m_library;
  35. Signature* m_function;
  36. };
  37.  
  38. void test_lib_func(string s)
  39. {
  40. cout << "called test_lib_func(" << s << ")\n";
  41. }
  42.  
  43. int main()
  44. {
  45. shared_ptr<library> lib = make_shared<library>();
  46. {
  47. library_function<void(string)> functor(lib, test_lib_func);
  48. functor("direct call before reset");
  49. lib.reset();
  50. functor("direct call after reset");
  51. cout << "functor about to go out of scope\n";
  52. }
  53.  
  54. lib = make_shared<library>();
  55. function<void(string)> func =
  56. library_function<void(string)>(lib, test_lib_func);
  57. func("std::function call before reset");
  58. lib.reset();
  59. func("std::function call after reset");
  60. return 0;
  61. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
creating library
called test_lib_func(direct call before reset)
called test_lib_func(direct call after reset)
functor about to go out of scope
destroying library
creating library
called test_lib_func(std::function call before reset)
called test_lib_func(std::function call after reset)
destroying library