home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / cplus / 18324 < prev    next >
Encoding:
Text File  |  1992-12-22  |  2.0 KB  |  53 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!psinntp!cci632!dwr
  3. From: dwr@cci632.cci.com (Donald W. Rouse II)
  4. Subject: Re: Can't I initialize a dynamically allocated object in its constructor?
  5. Message-ID: <1992Dec22.191446.24640@cci632.cci.com>
  6. Organization: [Computer Consoles, Inc., Rochester, NY
  7. References: <1992Dec17.205113.1180@IRO.UMontreal.CA>
  8. Date: Tue, 22 Dec 1992 19:14:46 GMT
  9. Lines: 42
  10.  
  11. In article <1992Dec17.205113.1180@IRO.UMontreal.CA> laviers@IRO.UMontreal.CA (Cocotte Minute) writes:
  12. >Hello,
  13. >
  14. >I have the following problem.
  15. >
  16. [ problem deleted ]
  17.  
  18. My off-the-top-of-my-head guess is that your problem is caused
  19. by lack of a copy constructor.
  20. When operator+ returns, the compiler probably invokes
  21. a copy constructor to return the value of the operation.
  22. Since you have not defined one, it creates a default copy
  23. constructor which just copies item and size, but does not
  24. allocate memory for *item, nor does it copy anything.
  25. Now, the returned value.item and retVect.item point to the
  26. same memory, so when retVect gets destructed, the array
  27. gets returned to the heap.  Now (v1+v2).item points to free space.
  28. Next, operator+ is called again.  When retVect is constructed,
  29. it gets memory from the heap, which just happens to be the
  30. memory that was previously freed.  If you do not initialize
  31. the array, it retains its old values, and everything looks great.
  32. (It isn't great, though; it just looks that way.)
  33. If you do initialize, then of course the old values get scrogged.
  34.  
  35. All of this is speculation on my part, except for that fact that
  36. you should define your own copy constructor:
  37.  
  38. Vector::Vector(Vector& v) { 
  39.    item = new double[v.size] ; 
  40.    size = v.size ;
  41.    printf("copy constructing\n");
  42.    for(int i=0;i<size;i++)item[i]=v.item[i];
  43. }
  44.  
  45. Hope this helps.
  46.  
  47. PS.  IMO, compilers should warn about this type of thing.
  48. I understand that g++ detects T operator=(T&) with no T(T&).
  49. Kudos to them.  All compilers should do this.
  50. It would also be nice if all compilers warned about
  51. creating default copy constructors when other constructors
  52. use "new".  Every little bit helps.
  53.