home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!spool.mu.edu!darwin.sura.net!jvnc.net!newsserver.technet.sg!nuscc!papaya!suresh
- From: suresh@papaya.iss.nus.sg (Suresh Thennarangam - Research Scholar)
- Subject: Re: Can't I initialize a dynamically allocated object in its constructor
- Message-ID: <1992Dec28.031532.4158@nuscc.nus.sg>
- Sender: usenet@nuscc.nus.sg
- Reply-To: suresh@iss.nus.sg (Suresh Thennarangam - Research Scholar)
- Organization: Institute of Systems Science, NUS, Singapore
- References: <1992Dec22.114251.6663@nuscc.nus.sg> <1992Dec27.200209.19143@news2.cis.umn.edu>
- Date: Mon, 28 Dec 1992 03:15:32 GMT
- Lines: 53
-
- In article <1992Dec27.200209.19143@news2.cis.umn.edu> hansen@myria.cs.umn.edu (David Hansen) writes:
- >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 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?
-
- I think you are right. I tried it out with my cfront2.1 on SUN4 and it does
- work. I omitted to realize that the copy constructor would be called before
- the automatic variable retVect went out of scope and that is really the way
- it should work.
-
- Regards,
-
-
- __
- (_ / / o_ o o |_
- __)/(_( __) (_(_ /_)| )_
-
-
-
-