Slimelite BBS

Re: cchar.hpp

Back to EMULATE

From Darin McBride · 1996-04-04 02:12 · #73660 in EMULATE

In reply to Re: cchar.hpp by Chris Downs

 CD>  Here's a better operator=

 CD>  cchar& cchar::operator=(const cchar& cch) {
 CD>   if (this == &cch) return *this;
 CD>   delete[] pchar;
 CD>   //set up your internal rep as before
 CD>   return *this;
 CD>  }

 EB> Also, although you didn't explicitly call it out, 
 EB> you've eliminated the redundant "if (pchar == NULL) 
 EB> delete[] pchar;" since delete[] is guaranteed to have 
 EB> no effect if called with a NULL argument.

While delete is guaranteed this behaviour, I like to avoid it when I can.  While I'm not going to go on a tirade on this one <GRIN: Bob, Fred>, I think that deleting already non-existant memory is 'bad'.  By taking this method, my code will be a little slower (but, really, with 66 million cycles to play with, it will rarely be noticed, especially over the strcpy call!), but I keep myself awake to 'is this a valid pointer right now?' types of questions.

 EB> The function returns a pointer to a local variable 
 EB> which, of course, is destroyed as soon as it goes out 
 EB> of scope.  Using a recent vintage Borland compiler 
 EB> under DOS gives a warning about a suspicious pointer 
 EB> conversion, but it compiles and links the code.  Here's the rest:

Borland C++ 4.52 complained about it returning a reference to a local variable.  I can't recall if that was a 'warning' or an 'error'.  Watcom 10.5 did similarily, and, IIRC, complained so bitterly that it refused to link (i.e., 'error').

 EB> explicitly setting the member pointer to NULL, we get a 
 EB> NULL pointer assignment.  It may seem a contrived 

Under Borland, 'cout << (char*)NULL' gives '(null)'.  What a brilliant idea.  :-)

Under Watcom, it gives a big SYS error (3125, I believe) under OS/2, and dies in a glorius explosion.  :-}

Personally, I think Watcom's way is more noticeable.  :-)

 EB> example, but I've seen it come up as a bug in the real 
 EB> world more often than "double deletion."  Is your 

Same here.  I've CAUSED similar bugs WAY too often.  :-)  This could be why I am prone to do things in a way that will absolutely die when I do something so stupid.  :-}


--- Maximus/2 3.01
 * Origin: Tanktalus' Tower BBS (PVT) (1:342/708)