ngo@tammy.harvard.edu (Tom Ngo) (11/15/90)
[Around 50 lines long] This is a summary of responses to my question, posted last week: | I have a class, A, of which multiple identical objects are typically | created. I would like to save memory and time by eliminating the need | for duplicate objects. An object would keep count of the number of | active pointers referencing it. Calls to the destructor would | decrement this count, and memory would be freed only on reaching a | zero count. | | Unix aside: This is analogous to how the link count works in ln, rm. | | I am having difficulty implementing this because in C++, memory | allocation and object initialization are distinct activities. Thus, | new() is invoked before construction, and delete(), after destruction. | | This seems like it ought to be a common problem, and I would | appreciate any pointers. I will keep a count of the pointers and | self-destruct when the last one is gone. (Ugh.) The replies fell into two categories: (1) Use a second class. That is, define a class (say, A_Wrapper) which has sole access to class A. It should contain only one data member, a *A. Then, put a reference count in A that gets initialized to 1 in A::A(). Whenever an A_Wrapper gets contructed, copied or destroyed, increment or decrement the refcount in A as appropriate. When the refcount goes to zero, delete the A object. (Described in "Using C++" by Bruce Eckel.) (2) Do not use a second class. Instead, write two new methods, perhaps called A::link() and A::unlink(), which increment and decrement the refcount. Have unlink() delete this when the refcount goes to zero. (This solution is used in InterViews, according to one person who responded.) Of these two solutions, the first seems safer since with the second solution, the onus is on the programmer to remember to link() and unlink() at all the right times. Also, the second solution seems to mandate that objects of class A be allocated explicitly via new, because at the end of it all we want to call A::unlink() instead of A::~A(). Please correct me via e-mail if I am wrong on this point. (Of course, one could argue that this fancy refcount business is useful only when new is being used.) Thanks to those who replied: bashford@scripps.edu (Don Bashford) jbuck@ohm.berkeley.edu (Joe Buck) Rob Sartin <sartin@hplabsz.hpl.hp.com> dh@ukc.ac.uk steve@taumet.com (Stephen Clamage) -- Tom Ngo ngo@harvard.harvard.edu 617/495-1768 lab number, leave message