Mail Archives: djgpp/2002/06/01/08:42:07
"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.
- Raw text -