Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

56 linhas
903B

  1. template<class T>
  2. class Ptr {
  3. struct RefCntObj {
  4. int count;
  5. T* obj;
  6. RefCntObj (T* q) { count = 1; obj = q; }
  7. };
  8. RefCntObj* p;
  9. void report () {
  10. std::cout << "refcnt = " << p->count << std::endl;
  11. }
  12. void increment () {
  13. p->count = p->count + 1;
  14. report();
  15. }
  16. void decrement () {
  17. p->count = p->count - 1;
  18. report();
  19. if (p->count==0) {
  20. delete p->obj; // Geht nicht fuer Felder!
  21. delete p;
  22. }
  23. }
  24. public:
  25. Ptr () { p=0; }
  26. Ptr (T* q) {
  27. p = new RefCntObj(q);
  28. report();
  29. }
  30. Ptr (const Ptr<T>& y) {
  31. p = y.p;
  32. if (p!=0) increment();
  33. }
  34. ~Ptr () {
  35. if (p!=0) decrement();
  36. }
  37. Ptr<T>& operator= (const Ptr<T>& y) {
  38. if (p!=y.p) {
  39. if (p!=0) decrement();
  40. p = y.p;
  41. if (p!=0) increment();
  42. }
  43. return *this;
  44. }
  45. T& operator* () { return *(p->obj); }
  46. T* operator-> () { return p->obj; }
  47. };