fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class matrix_rc
  6. {
  7. public:
  8. matrix_rc()
  9. {
  10. inst = new instance;
  11. }
  12.  
  13. matrix_rc(const matrix_rc& other)
  14. {
  15. cout << "Лёгкое копирование matrix_rc ("
  16. << (other.inst
  17. ? "refcount: " + to_string(other.inst->refcount) + " -> " + to_string(other.inst->refcount + 1)
  18. : "пустой")
  19. << ")." << endl;
  20.  
  21. if (other.inst) other.inst->refcount++;
  22. this->inst = other.inst;
  23. }
  24.  
  25. ~matrix_rc()
  26. {
  27. cout << "Лёгкое уничтожение matrix_rc ("
  28. << (inst
  29. ? "refcount: " + to_string(inst->refcount) + " -> " + to_string(inst->refcount - 1)
  30. : "пустой")
  31. << ")." << endl;
  32.  
  33. if (inst && --inst->refcount == 0) delete this->inst;
  34. }
  35.  
  36. private:
  37. class instance
  38. {
  39. friend class matrix_rc;
  40. instance()
  41. {
  42. cout << "Тяжёлое создание matrix_rc::instance (refcount: 1)." << endl;
  43. data = new double[1000 * 1000];
  44. refcount = 1;
  45.  
  46. }
  47.  
  48. ~instance()
  49. {
  50. cout << "Тяжёлое уничтожение matrix_rc::instance." << endl;
  51. delete[] data;
  52. }
  53.  
  54. double* data;
  55. size_t refcount;
  56. };
  57.  
  58. instance* inst;
  59. };
  60.  
  61. int main()
  62. {
  63. vector<matrix_rc> v;
  64. v.push_back(matrix_rc());
  65. return 0;
  66. }
Success #stdin #stdout 0s 4908KB
stdin
Standard input is empty
stdout
Тяжёлое создание matrix_rc::instance (refcount: 1).
Лёгкое копирование matrix_rc (refcount: 1 -> 2).
Лёгкое уничтожение matrix_rc (refcount: 2 -> 1).
Лёгкое уничтожение matrix_rc (refcount: 1 -> 0).
Тяжёлое уничтожение matrix_rc::instance.