Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!caen!news.cs.indiana.edu!att!ucbvax!pasteur!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++ Subject: Re: Want pointers on intelligent pointers Message-ID: <12135@pasteur.Berkeley.EDU> Date: 19 Mar 91 03:45:01 GMT References: <838@antares.Concordia.CA> Sender: news@pasteur.Berkeley.EDU Reply-To: jbuck@galileo.berkeley.edu (Joe Buck) Lines: 47 In article <838@antares.Concordia.CA>, marcap@antares.concordia.ca ( MARC ANDREW PAWLOWSKY ) writes: |> I am trying to make a smart class so objects will not delete themselves |> if someone is pointing to them. |> |> I have been following the discussion so far and came up with |> the following: |> |> Each object keeps a counter which indicates how many objects |> are pointing to it. To keep the counter valid it is necessary |> for the class to have its own copy, and reference routines. You're close. But you need two classes, SmartClassRep stores the actual data and SmartClass stores a pointer to it. When you copy SmartClass objects around you adjust the reference count. Here's part of the job: class SmartClassRep { friend SmartClass; // make all members private int refCount; SmartClassRep() : refCount(0) { ... } }; class SmartClass { private: SmartClassRep *p; public: // assignment operator SmartClass& operator=(const SmartClass& arg) { arg.p->refCount++; if (--p->refCount == 0) delete p; p = arg.p; } // copy constructor SmartClass(const SmartClass& arg) { p = arg.p; p->refCount++; } // destructor ~SmartClass() { if (--p->refCount == 0) delete p; } } -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck