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