fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct AbstractResource {
  6. int ref_count;
  7. virtual void do_something() = 0;
  8. AbstractResource() : ref_count(0) {}
  9. virtual ~AbstractResource(){}
  10. };
  11.  
  12. struct Resource0 : public AbstractResource {
  13. void do_something(){
  14. cout << "Do somthing with Resource0 at " << this << endl;
  15. }
  16. Resource0() : AbstractResource() {
  17. cout << "Created : Resource0 at " << this << endl;
  18. }
  19. ~Resource0(){
  20. cout << "Clean-uped : Resource0 at " << this << endl;
  21. }
  22. };
  23.  
  24. struct Resource1 : public AbstractResource {
  25. void do_something(){
  26. cout << "Do somthing with Resource1 at " << this << endl;
  27. }
  28. Resource1() : AbstractResource() {
  29. cout << "Created : Resource1 at " << this << endl;
  30. }
  31. ~Resource1(){
  32. cout << "Clean-uped : Resource1 at " << this << endl;
  33. }
  34. };
  35.  
  36. struct Resource {
  37. AbstractResource *delegatee;
  38. void do_something() {
  39. delegatee->do_something();
  40. }
  41. Resource(AbstractResource *resource)
  42. : delegatee(resource) {
  43. (delegatee->ref_count)++;
  44. }
  45. Resource(const Resource &orig)
  46. : delegatee(orig.delegatee) {
  47. (delegatee->ref_count)++;
  48. }
  49. Resource &operator=(const Resource &rhs){
  50. if(delegatee != rhs.delegatee){
  51. if(--(delegatee->ref_count) <= 0){
  52. delete delegatee;
  53. }
  54. delegatee = rhs.delegatee;
  55. (delegatee->ref_count)++;
  56. }
  57. return *this;
  58. }
  59. ~Resource() {
  60. if(--(delegatee->ref_count) < 1){
  61. delete delegatee;
  62. }
  63. }
  64. };
  65.  
  66. struct ResourceManager {
  67. static Resource get_resource(const int &type){
  68. return Resource((type != 0)
  69. ? (AbstractResource *)new Resource1()
  70. : (AbstractResource *)new Resource0());
  71. }
  72. };
  73.  
  74. int main() {
  75. Resource r0(ResourceManager::get_resource(0));
  76. r0.do_something();
  77.  
  78. Resource r1(ResourceManager::get_resource(1));
  79. r1.do_something();
  80.  
  81. {
  82. Resource r0_copy(r0);
  83. r0_copy.do_something();
  84.  
  85. Resource r1_another(ResourceManager::get_resource(1));
  86. r1_another.do_something();
  87. }
  88.  
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 2860KB
stdin
Standard input is empty
stdout
Created : Resource0 at 0x9e79008
Do somthing with Resource0 at 0x9e79008
Created : Resource1 at 0x9e79018
Do somthing with Resource1 at 0x9e79018
Do somthing with Resource0 at 0x9e79008
Created : Resource1 at 0x9e79028
Do somthing with Resource1 at 0x9e79028
Clean-uped : Resource1 at 0x9e79028
Clean-uped : Resource1 at 0x9e79018
Clean-uped : Resource0 at 0x9e79008