fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <functional>
  4.  
  5. using namespace std;
  6.  
  7. struct cleanup {
  8. void operator() (int *i) {
  9. std::cout << "Cleaning up resource: " << i << "(" << *i << ")"
  10. << std::endl;
  11. // Do the work for releasing resource
  12. delete i;
  13. }
  14. };
  15.  
  16. void use_temporary_resource(std::shared_ptr<int> resource,
  17. const int &proof, const int &multiple) {
  18. int &i = *resource;
  19. std::cout << "Proof " << proof << ", using the resource: " << i << std::endl;
  20. std::cout << i << "*" << multiple << "=" << i*multiple << std::endl;
  21. }
  22.  
  23. int main() {
  24. std::shared_ptr<int> tempResource1(new int(1), cleanup());
  25. std::cout << "Resource 1 created: "
  26. << tempResource1.get() << "(" << *tempResource1 << ")" << std::endl;
  27.  
  28. // Resource is held onto with bind
  29. std::function<void(int i)> proof1 = std::bind(use_temporary_resource,
  30. tempResource1,
  31. 1,
  32. std::placeholders::_1);
  33. // If it wasn't this would close the resource
  34. tempResource1.reset();
  35. proof1(1);
  36. proof1(2);
  37. {
  38. std::shared_ptr<int> tempResource2(new int(2), cleanup());
  39. // Resource is held onto with bind
  40. std::function<void(int i)> proof2 = std::bind(use_temporary_resource,
  41. tempResource2,
  42. 2,
  43. std::placeholders::_1);
  44. // If it wasn't this would close the resource
  45. tempResource2.reset();
  46. proof2(10);
  47. proof2(20);
  48. } // Once scope goes away from proof2, the resource is released.
  49. std::cout << "Resource 2 should have been released after exiting scope containing proof2 (here)."
  50. << std::endl;
  51.  
  52. std::shared_ptr<int> tempResource3(new int(3), cleanup());
  53. std::cout << "Resource 3 created: "
  54. << tempResource3.get() << "(" << *tempResource3 << ")" << std::endl;
  55. // Show that normally a resource will disapear if not placed in bind
  56. tempResource3.reset();
  57. std::cout << "Exiting..." << std::endl;
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
Resource 1 created: 0x94b7008(1)
Proof 1, using the resource: 1
1*1=1
Proof 1, using the resource: 1
1*2=2
Proof 2, using the resource: 2
2*10=20
Proof 2, using the resource: 2
2*20=40
Cleaning up resource: 0x94b7048(2)
Resource 2 should have been released after exiting scope containing proof2 (here).
Resource 3 created: 0x94b7048(3)
Cleaning up resource: 0x94b7048(3)
Exiting...
Cleaning up resource: 0x94b7008(1)