Mail Archives: djgpp/2002/06/11/20:15:02
"Jesper Lund" <jl1204 AT worldonline DOT dk> wrote in message news:<5P2K8.30975$4f4 DOT 1197748 AT news000 DOT worldonline DOT dk>...
> "Jason" <jr_4226 AT yahoo DOT com> wrote:
>
> > As a followup, I have traced the problem back to the CBoard instance
> calling
> > the destructor straight after calling the constructor, upon 'push'ing
> CBoard
> > onto the vector container. This means that my 'new'ly created BoardSpace
> is
> > 'delete'd. Is this C++ standard behaviour? If so, how do I get around
> > that?
>
> Your class has a pointer among the member variables, but you do not have a
> copy constructor which copies (clones) the memory that the pointer variable
> points to. The default copy constructor copies each variable, which in this
> case means the pointer value (but not the memory pointed to). After the
> copy, you have two class objects pointing to the same block of memory, but
> when one object is destructed, the other points to a memory block which is
> no longer used. Hence, the crash.
>
> Solutions to this problem involve 'smart pointers' (like shared_ptr at
> www.boost.org, for instance), or virtual constructors (which do the
> requisite cloning), see Stroustrup, "The C++ programming Language", 3rd ed,
> pages 424-425.
>
> By the way, as a general rule, whenever you need to define a destructor, you
> also need to define a copy constructor and copy assignment operator.
Sorry it took so long for me to reply, but I was away from my PC for a
while.
A lot of what you said I don't know about as yet, so I'll be doing a
bit of study into these areas. I havent used copy constructors
(didn't even know they were required - I though C++ made class
instances as little individual bundles of member variables & functions
that nothing had access to unless they were public or friend members?
How disappointing to find out that this isn't the case!)
Thanks you for your informative reply - at least I now know what track
to take to solve the problem!
Jase.
- Raw text -