home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!gatech!concert!uvaarpa!murdoch!uvacs.cs.Virginia.EDU!rad2r
- From: rad2r@uvacs.cs.Virginia.EDU (Robert DeLine)
- Subject: Style of writing container classes
- Message-ID: <1992Sep13.194422.23934@murdoch.acc.Virginia.EDU>
- Sender: usenet@murdoch.acc.Virginia.EDU
- Organization: University of Virginia Computer Science Department
- Date: Sun, 13 Sep 1992 19:44:22 GMT
- Lines: 50
-
-
- Today I was bitten by a bug in a container class I wrote, a general
- linked list. I had used a reference to actually implement the
- containment, e.g.
-
- template <class TYPE>
- struct LinkedListNode
- {
- TYPE& data;
- LinkedListNode* prev;
- LinkedListNode* next;
- };
-
- This worked fine for things like LinkedList<String> or
- LinkedList<double> but when I did LinkedList<MyClass*>, I ran into the
- bug. I has written a seemingly innocent loop:
-
- LinkedList<MyClass*> list;
- for (blah; blah; blah) {
- MyClass* mptr = new MyClass(whatever);
- list.append(mptr);
- }
-
- But because I was storing a *reference* to the data (to a pointer in
- this case), I ended up with a linked list which contained n copies of
- the last thing added. This is because the reference in this case was a
- reference to a *pointer* that kept changing. Sigh. Live and learn.
-
- My solution was to change the declaration to
-
- TYPE data;
-
- In other words, I copy the data. This means (1) the user could be
- copying large amounts of data and (2) any class you use *must* have a
- copy operator defined. I don't think this is so bad, since you can
- always declare a linked list of pointers to your data type, which
- elleviates both problems.
-
- My question is (bet you were beginning to wonder if there was a
- question): is this the way most people write their container classes?
- Do you usually copy, knowing the user can give you a pointer? Or do
- you use a pointer, knowing the user can call new by himself? Are
- references just a bad idea in this case, or did I use them incorrectly?
-
- Your thoughts, experience and advice greatly appreciated.
-
- --
- Rob DeLine
- Computer Science, University of Virginia
- deline@Virginia.EDU
-