delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2002/06/01/08:42:07

From: "Jesper Lund" <jl1204 AT worldonline DOT dk>
Newsgroups: comp.os.msdos.djgpp
References: <3cf6c05e_1 AT news DOT iprimus DOT com DOT au> <3cf6d9d1$1_1 AT news DOT iprimus DOT com DOT au>
Subject: Re: Vector of Classes issue in GCC 3.1
Lines: 29
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.50.4807.1700
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4807.1700
Message-ID: <5P2K8.30975$4f4.1197748@news000.worldonline.dk>
Date: Sat, 1 Jun 2002 14:07:17 +0200
NNTP-Posting-Host: 212.54.81.162
X-Complaints-To: news-abuse AT wol DOT dk
X-Trace: news000.worldonline.dk 1022933313 212.54.81.162 (Sat, 01 Jun 2002 14:08:33 MET DST)
NNTP-Posting-Date: Sat, 01 Jun 2002 14:08:33 MET DST
Organization: Customer of Tiscali A/S
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

"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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019