delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2002/06/12/14:33:01

From: Nick <jp_prongs AT yahoo DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Vector of Classes issue in GCC 3.1
Date: Wed, 12 Jun 2002 13:13:07 -0400
Organization: MindSpring Enterprises
Lines: 28
Message-ID: <3D078123.98D37812@yahoo.com>
References: <3cf6c05e_1 AT news DOT iprimus DOT com DOT au> <3cf6d9d1$1_1 AT news DOT iprimus DOT com DOT au> <5P2K8.30975$4f4 DOT 1197748 AT news000 DOT worldonline DOT dk> <5576bd2c DOT 0206111609 DOT 2facd787 AT posting DOT google DOT com>
NNTP-Posting-Host: a5.f7.82.37
Mime-Version: 1.0
X-Server-Date: 12 Jun 2002 17:13:27 GMT
X-Mailer: Mozilla 4.75 [en] (Win98; U)
X-Accept-Language: en
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Let's say you have a class like:

class foo {
	char *a;
	foo() { a = malloc(100); }
	~foo() { free(a); }
};

Then doing this:

foo *bar = new foo;
foo *baz = new foo(bar);
delete bar;

will cause baz.a to point to a free()d memory block, messing up your program. This is because, by
default, baz.a will be the same as bar.a. To fix that, you can use this class:

class foo2 {
	char *a;
	foo() { a = malloc(100); }
	foo(foo& orig) { a = malloc(100); memcpy(a, orig.a, 100); }
	foo& operator=(foo& orig) { memcpy(a, orig.a, 100); }
	~foo() { free(a); }
};

The foo(foo& orig), the copy constructor, allocates a new block and copies the original object's
block to it. The operator= causes statements like "foo baz = bar;" to work OK, by copying the data
pointed to by bar.a to baz.a.

- Raw text -


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