home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!math.fu-berlin.de!fauern!ira.uka.de!ira.uka.de!slsvaat!josef!kanze
- From: kanze@us-es.sel.de (James Kanze)
- Subject: Re: question on REFERENCES
- In-Reply-To: kestes@nswc-wo.nswc.navy.mil's message of Tue, 17 Nov 1992 14:10:55 GMT
- Message-ID: <KANZE.92Nov18170843@slsvdnt.us-es.sel.de>
- Sender: news@us-es.sel.de
- Organization: SEL
- References: <1992Nov17.073603.5235@murdoch.acc.Virginia.EDU> <75096@hydra.gatech.EDU>
- <1992Nov17.141055.19557@relay.nswc.navy.mil>
- Date: 18 Nov 92 17:08:43
- Lines: 45
-
- In article <1992Nov17.141055.19557@relay.nswc.navy.mil>
- kestes@nswc-wo.nswc.navy.mil (Kent Estes) writes:
-
- |> I am working on a function that references objects via id. Upon finding
- |> an object, it returns a reference to that object. My question is :
- |> if the object is not found, what is the best way to handle this. If
- |> I were returning pointers to objects, all I would have to do is
- |> return NULL.
-
- Two possibilities:
-
- Add the element being looked up to the set of objects, with a default
- value, and return this. This is a good solution for associative
- arrays, for example, where the operator[] never fails.
-
- Or treat such a reference as an error, and do your error handling
- thing. Exceptions would be nice here, but while we're waiting, I
- generally use a call back function. Note, however, that if the
- call-back function returns to where it was called from, you'd better
- have something to return anyway. (A static value would do the trick.
- The important thing is that the user is supposed to do something in
- the call-back function so that he won't use the reference later
- anyway.)
-
- To give a concrete example, from my assocative array class:
-
- class AssocArray
- {
- public :
- DataType& operator[]( const KeyType& ) ;
- const DataType& operator[]( const KeyType& ) const ;
- int contains( const KeyType& ) const ;
- } ;
-
- The first operator[] uses the first solution. The second operator[],
- which will be used on constant objects, uses the second solution, with
- a default call-back function which aborts the program with an error
- message. The contains function is there so that the user can find out
- whether the key is present *before* creating it (in a non-const
- object) or calling the call-back function (in a const object).
- --
- James Kanze GABI Software, Sarl.
- email: kanze@us-es.sel.de 8 rue du Faisan
- 67000 Strasbourg
- France
-