home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13612 < prev    next >
Encoding:
Text File  |  1992-09-14  |  2.1 KB  |  61 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!gatech!concert!uvaarpa!murdoch!uvacs.cs.Virginia.EDU!rad2r
  3. From: rad2r@uvacs.cs.Virginia.EDU (Robert DeLine)
  4. Subject: Style of writing container classes
  5. Message-ID: <1992Sep13.194422.23934@murdoch.acc.Virginia.EDU>
  6. Sender: usenet@murdoch.acc.Virginia.EDU
  7. Organization: University of Virginia Computer Science Department
  8. Date: Sun, 13 Sep 1992 19:44:22 GMT
  9. Lines: 50
  10.  
  11.  
  12. Today I was bitten by a bug in a container class I wrote, a general
  13. linked list.  I had used a reference to actually implement the
  14. containment, e.g.
  15.  
  16.     template <class TYPE>
  17.     struct LinkedListNode
  18.     {
  19.         TYPE& data;
  20.         LinkedListNode* prev;
  21.         LinkedListNode* next;
  22.     };
  23.  
  24. This worked fine for things like LinkedList<String> or
  25. LinkedList<double> but when I did LinkedList<MyClass*>, I ran into the
  26. bug.  I has written a seemingly innocent loop:
  27.  
  28.     LinkedList<MyClass*> list;
  29.     for (blah; blah; blah) {
  30.         MyClass* mptr = new MyClass(whatever);
  31.         list.append(mptr);
  32.     }
  33.  
  34. But because I was storing a *reference* to the data (to a pointer in
  35. this case), I ended up with a linked list which contained n copies of
  36. the last thing added.  This is because the reference in this case was a
  37. reference to a *pointer* that kept changing.  Sigh.  Live and learn.
  38.  
  39. My solution was to change the declaration to
  40.  
  41.         TYPE data;
  42.  
  43. In other words, I copy the data.  This means (1) the user could be
  44. copying large amounts of data and (2) any class you use *must* have a
  45. copy operator defined.  I don't think this is so bad, since you can
  46. always declare a linked list of pointers to your data type, which
  47. elleviates both problems.
  48.  
  49. My question is (bet you were beginning to wonder if there was a
  50. question): is this the way most people write their container classes?
  51. Do you usually copy, knowing the user can give you a pointer?  Or do
  52. you use a pointer, knowing the user can call new by himself?  Are
  53. references just a bad idea in this case, or did I use them incorrectly?
  54.  
  55. Your thoughts, experience and advice greatly appreciated.
  56.  
  57. -- 
  58. Rob DeLine
  59. Computer Science, University of Virginia
  60. deline@Virginia.EDU
  61.