home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 3CTDSTK.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  1KB  |  53 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. class Stack {
  7. public:
  8.     Stack() { }
  9.     ~Stack() { }
  10.     int pop() { return 1; }
  11.     void push(int) { }
  12. };
  13.  
  14. class CountedStack {
  15. public:
  16.     CountedStack(): rep(new CountedStackRep) { }
  17.     int pop() { return rep->rep->pop(); }
  18.     void push(int i) { rep->rep->push(i); }
  19.     CountedStack(const CountedStack &c) {
  20.     rep = c.rep;
  21.     rep->count++;
  22.     }
  23.     CountedStack(const Stack &c) {
  24.     rep = new CountedStackRep(new Stack(c));
  25.     }
  26.     operator Stack() { return *(rep->rep); }
  27.     ~CountedStack() {
  28.     if (--rep->count <= 0) delete rep;
  29.     }
  30.     CountedStack &operator=(const CountedStack &c) {
  31.     c.rep->count++;
  32.     if (--rep->count <= 0) delete rep;
  33.     rep = c.rep;
  34.     return *this;
  35.     }
  36. private:
  37.     struct CountedStackRep {
  38.     int count;
  39.     Stack *rep;
  40.     CountedStackRep(Stack *s = 0) {
  41.         rep = s? s: new Stack; count = 1;
  42.     }
  43.     } *rep;
  44. };
  45.  
  46. int main() {
  47.     CountedStack a, b;
  48.     Stack s, t;
  49.     a = b;
  50.     b = s;
  51.     t = b;
  52. }
  53.