home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- From: nikki@trmphrst.demon.co.uk (Nikki Locke)
- Path: sparky!uunet!pipex!demon!trmphrst.demon.co.uk!nikki
- Distribution: world
- Subject: Re: Reference counting for vectors, (Tony Hansen's book).
- References: <TMB.92Aug16160535@arolla.idiap.ch>
- X-Mailer: cppnews $Revision: 1.14 $
- Organization: Trumphurst Ltd.
- Lines: 96
- Date: Wed, 19 Aug 1992 15:54:11 +0000
- Message-ID: <714264851snx@trmphrst.demon.co.uk>
- Sender: usenet@gate.demon.co.uk
-
-
- In article <TMB.92Aug16160535@arolla.idiap.ch> tmb@idiap.ch writes:
-
- > Counted.h
- >
- > #ifndef __COUNTED__
- > #define __COUNTED__
- >
- > template <class T>
- > struct Counted {
- > private:
- > int *count;
- > T *object;
- > void drop() {
- > if(!count) return;
- > (*count)--;
- > if(*count<=0) {
- > delete count;
- > delete object;
- > count=0;
- > object=0;
- > }
- > }
- > void acquire() {
- > (*count)++;
- > }
- > public:
- > Counted() {
- > count=0;
- > object=0;
- > }
- > Counted(T *object):object(object) {
- > count = new int(1);
- > }
- > ~Counted() {
- > drop();
- > }
- > Counted(Counted &other) {
- > count=other.count;
- > object=other.object;
- > acquire();
- > }
- > Counted &operator=(Counted &other) {
- > drop();
- > count=other.count;
- > object=other.object;
- > acquire();
- > return *this;
- > }
- I think this copy operator contains the classic copy operator bug - try
- assigning a Counted object to itself - the object will be deleted before
- copying. Try ...
-
- Counted &operator=(Counted &other) {
- other.acquire();
- drop();
- count=other.count;
- object=other.object;
- return *this;
- }
- Mind you, there is still a bug here - try
-
- Counted<Thing> a, b;
-
- a = b; // core dump ?
-
- The fix is for acquire to check count is not NULL before doing (*count)++;
-
- >
- > T &operator*() {return *object;}
- > T *operator->() {return object;}
- > operator T() {return *object;}
- >
- >
- > // do _not_ provide "operator T*()"
- > };
- >
- > #endif
- >
-
- The original author clearly stated that the program was not tested, but I
- thought I ought to point out these problems so that others didn't copy the
- mistakes.
-
- Mind you, I haven't even compiled the code, let alone tested it, so I am
- even more likely to be wrong !
-
- [ Hobby horse of the week ... ]
- However, if I am right, think about how useful code review is in picking
- up such obscure bugs, and how cheap compared to hours of testing !
- ---
- Nikki Locke | | nikki@trmphrst.demon.co.uk
- Trumphurst Ltd. | Tel: +44 (0)691-670318 | nikki@cix.compulink.co.uk
- PC and Unix consultancy | Fax: +44 (0)691-670316 | nikki@kewill.co.uk
- trmphrst.demon.co.uk is NOT affiliated with ANY other sites at demon.co.uk.
- Demon.co.uk is a dial-up subscription access point to the Internet.
-