Mail Archives: djgpp/1998/02/09/21:19:43
Geoffrey French wrote:
>
> I have a bit of a strange problem with DJGPP :
>
[snip class definition]
>
> int main()
> {
> TC x, *y;
>
> x = TC(1);
> y = new TC(1);
> }
>
> I find that upon calling the constructor TC(long i) in the line 'x =
> TC(1)' not only is the constructor called, but the destructor is
> called straight afterwards (!), thus deleteing the reserved memory for
> the variable a. However, in the line 'y = new TC(1)' only the
> constructor is called. It seems that whenever you say 'c =
> TClass(...)' the TClass destructor is called as well as the
> constructor.
>
> Can anyone help?
Of course. This is standard C++ stuff here and is not strictly relevant
to DJGPP, but I'm learning C++ as well and this topic just recently came
up in class. The line "x = TC(1);" is broken down by the compiler into
three parts:
First, it creates a temporary unnamed object of type TC, and calls the
constructor with a value of 1. The scope of this object is the
statement in which it occurs. The object can be treated more or less
like a numeric constant: more because it has no existence outside the
statement, but less because, unlike a numeric constant, the program
actually creates it at runtime.
Second, it assigns the temporary unnamed object to x using the default
copy constructor.
Third, the temporary unnamed object is now out of scope, so its
destructor is called. Since x contains a bit-for-bit copy of the data
in this object, x's data is invalidated as a result.
The solution to this problem is to overload the '=' operator for class
TC to allocate new memory instead of simply copying the pointer.
The reason the second statement works is that objects allocated with new
are not destroyed until delete is called.
Hope this helps!
--
---------------------------------------------------------------------
| John M. Aldrich | "Always listen to experts. They'll |
| aka Fighteer I | tell you what can't be done, and why.|
| mailto:fighteer AT cs DOT com | Then do it." |
| http://www.cs.com/fighteer/| - Lazarus Long |
---------------------------------------------------------------------
- Raw text -