home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!utcsri!torn!spool.mu.edu!umn.edu!myria.cs.umn.edu!hansen
- From: hansen@myria.cs.umn.edu (David Hansen)
- Subject: Re: Can't I initialize a dynamically allocated object in its constructor
- Message-ID: <1992Dec27.200209.19143@news2.cis.umn.edu>
- Sender: news@news2.cis.umn.edu (Usenet News Administration)
- Nntp-Posting-Host: myria.cs.umn.edu
- Organization: University of Minnesota
- References: <1992Dec22.114251.6663@nuscc.nus.sg>
- Date: Sun, 27 Dec 1992 20:02:09 GMT
- Lines: 43
-
- In article <1992Dec22.114251.6663@nuscc.nus.sg>, suresh@papaya.iss.nus.sg (Suresh Thennarangam - Research Scholar) writes:
- [... most of included code deleted ...]
- |> >
- |> > Vector Vector::operator+ (Vector& a){
- |> > if (getsize() != a.getsize()){
- |> > printf("operator '+':Vectors are not of the same size.\n");
- |> > exit(0);
- |> > }
- |> > Vector retVect(getsize()) ;
- |> > for (int i = 0 ; i < a.getsize() ; i++){
- |> > retVect.item[i] = item[i] + a.item[i] ;
- |> > }
- |> > return retVect ;
- |> > }
- |> >
- |> My apologies for including the entire code above ....
- |> Also to make things easier I have moved the function
- |> Vector Vector::operator+() to the bottom.
- |>
- |> My point:
- |>
- |> retVect used above is a automatic variable that will go out of scope
- |> as soon as the function Vector::operator+() is exited and it's
- |> destructor will be called which will deallocate the memory
- |> that was allocated by the constructor. Although the returned
- |> Vector object is a copy and will have a valid item pointer, it will
- |> be pointing to deallocated data.
-
- Ummm, I don't think so. True, retVect is automatic and will be destroyed when
- it leaves scope. However, at least on _my_ system (CenterLine ObjectCenter),
- the copy constructor is called _before_ retVect is destroyed. The copy is
- valid. I would hope this is the way it is supposed to work...
-
- What you describe is the problem that existed _before_ the copy constructor
- was added. Since none was defined, the compiler generated one which simply
- performed a memberwise initialization of the copy. Since one of the members
- is a pointer to some memory which is then deallocated before the copy is used,
- we have the classic "dangling pointer." The copy constructor allocates its
- own memory for the pointer, which is then freed when the temporary is destroyed.
-
- Or is there something else I'm missing?
-
- -=Dave
-