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

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!utcsri!torn!spool.mu.edu!umn.edu!myria.cs.umn.edu!hansen
  3. From: hansen@myria.cs.umn.edu (David Hansen)
  4. Subject: Re: Can't I initialize a dynamically allocated object in its constructor
  5. Message-ID: <1992Dec27.200209.19143@news2.cis.umn.edu>
  6. Sender: news@news2.cis.umn.edu (Usenet News Administration)
  7. Nntp-Posting-Host: myria.cs.umn.edu
  8. Organization: University of Minnesota
  9. References:  <1992Dec22.114251.6663@nuscc.nus.sg>
  10. Date: Sun, 27 Dec 1992 20:02:09 GMT
  11. Lines: 43
  12.  
  13. In article <1992Dec22.114251.6663@nuscc.nus.sg>, suresh@papaya.iss.nus.sg (Suresh Thennarangam - Research Scholar) writes:
  14. [... most of included code deleted ...]
  15. |> > 
  16. |> > Vector Vector::operator+ (Vector& a){
  17. |> >    if (getsize() != a.getsize()){
  18. |> >       printf("operator '+':Vectors are not of the same size.\n");
  19. |> >       exit(0);
  20. |> >    }
  21. |> >    Vector retVect(getsize()) ;
  22. |> >    for (int i = 0 ; i < a.getsize() ; i++){
  23. |> >       retVect.item[i] = item[i] + a.item[i] ;
  24. |> >    }
  25. |> >    return retVect ;
  26. |> > }
  27. |> > 
  28. |> My apologies for including  the entire code above ....
  29. |> Also to make things easier I have moved the function  
  30. |> Vector Vector::operator+() to the bottom.
  31. |> 
  32. |> My point:
  33. |> 
  34. |> retVect used above is a automatic variable that will go out of scope
  35. |> as soon as the function Vector::operator+() is exited and it's 
  36. |> destructor will be called which will deallocate the memory
  37. |> that was allocated by the constructor. Although the returned
  38. |> Vector object is a copy and will have a valid item pointer, it will 
  39. |> be pointing to deallocated data.
  40.  
  41. Ummm, I don't think so.  True, retVect is automatic and will be destroyed when
  42. it leaves scope.  However, at least on _my_ system (CenterLine ObjectCenter),
  43. the copy constructor is called _before_ retVect is destroyed.  The copy is
  44. valid.  I would hope this is the way it is supposed to work...
  45.  
  46. What you describe is the problem that existed _before_ the copy constructor
  47. was added.  Since none was defined, the compiler generated one which simply
  48. performed a memberwise initialization of the copy.  Since one of the members
  49. is a pointer to some memory which is then deallocated before the copy is used,
  50. we have the classic "dangling pointer."  The copy constructor allocates its
  51. own memory for the pointer, which is then freed when the temporary is destroyed.
  52.  
  53. Or is there something else I'm missing?
  54.  
  55.                     -=Dave
  56.