home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!zaphod.mps.ohio-state.edu!not-for-mail
- From: ren@function.mps.ohio-state.edu (Liming Ren)
- Newsgroups: comp.lang.c++
- Subject: Re: Matrix Addition Was Re: Complex Addition.
- Date: 21 Dec 1992 20:46:23 -0500
- Organization: Department of Mathematics, The Ohio State University
- Lines: 56
- Message-ID: <1h5s1fINNa65@function.mps.ohio-state.edu>
- References: <1992Dec11.232954.7071@borland.com> <36223@sophia.inria.fr> <1992Dec17.204049.20009@murdoch.acc.Virginia.EDU>
- NNTP-Posting-Host: function.mps.ohio-state.edu
- Keywords: operator, memory leak
-
-
- In article <1992Dec17.204049.20009@murdoch.acc.Virginia.EDU> gs4t@virginia.edu (Gnanasekaran Swaminathan) writes:
- >One technique advocated several times in this forum and
- >by several good books is to use reference counting and
- >return by value in case of big objects like Matrix.
- >
- >For example,
- >
- >class Matrix {
- > struct MatRep {
- > int ref;
- > int rows, cols;
- > double* d;
- >
- > MatRep (int r, int c)
- > : ref(1), rows(r), cols(c), d(new double[rows*cols]) {}
- > ~MatRep () { delete [] d; }
- > }* rep;
- >public:
- > Matrix (int r, int c): rep(new MatRep(r,c)) {}
- > Matrix (const Matrix& m): rep (m.rep) { ++rep->ref; }
- > ~Matrix () { if (--rep->ref == 0) delete rep; }
- >
- > double operator () (int i, int j) { return rep->d[i*rep->rows+j]; }
- > Matrix& operator = (const Matrix& m) {
- > if (this != &m) {
- > this->Matrix::~Matrix (); // self destruct
- > rep = m.rep; ++rep->ref;
- > }
- > return *this;
- > }
- >
- > friend Matrix operator + (const Matrix& a, const Matrix& b);
- >};
- >
- >// note the return by value here
- >Matrix operator + (const Matrix& a, const Matrix& b)
- >{
- > Matrix sum (a.rep->rows, a.rep->cols);
- > for (int i=0; i < sum.rep->rows * sum.rep->cols; i++)
- > sum.rep->d[i] = a.rep->d[i] + b.rep->d[i];
- > return sum;
- >}
- I am new to c++, my questions are:
- (1) In the destructor ~Matrix(), what happens to the memory pointed by d? It is my understanding
- that the memory pointed by d should also be deleted explicitly. Although I am not quite sure.
-
- (2)In the operator + definition, sum.ref is initialized to 1. In order to be alive after exiting
- the function, the sum.ref at least should be 2. Where is the ref incremented exactly and by which
- function?
-
- Thanks for your help!
-
-
-
-
-