POV-Ray : Newsgroups : povray.off-topic : Adventures with C++ : Re: Adventures with C++ Server Time
29 Jul 2024 00:29:16 EDT (-0400)
  Re: Adventures with C++  
From: Orchid Win7 v1
Date: 1 Jun 2013 04:17:24
Message: <51a9ae14@news.povray.org>
On 31/05/2013 09:41 PM, Warp wrote:
> Orchid Win7 v1<voi### [at] devnull>  wrote:
>> To be clear... I only need to do explicit deallocation if I've done
>> explicit allocation in the first place, right?
>
> Every 'new' must have a correspondent 'delete'. If you don't write 'new'
> then you don't have to worry about any deletes either.
>
> Of course the exception to this is if you are using a smart pointer like
> std::shared_ptr or std::unique_ptr, in which case you do write 'new',
> but let the smart pointer do the 'delete' for you.
>
> If you really need to explicitly allocate memory, then it's usually a
> good idea to use such a smart pointer, because they will make sure that
> they will delete the object when the last smart pointer to it dies, and
> delete it only once.
>
> The thing is, even if you have written one 'new' and one 'delete' in your
> code, the object might be being deleted more than once. This is because of
> the wonderful thing in C++ that is copying and assigning of classes.

Without revealing too many details about the product I'm working on, it 
deals with byte-level processing of binary protocol data. So there's A 
LOT of char* variables floating around the place. In short, it's just 
the sort of code where a tiny bug will make the program output gibberish 
or crash spectacularly. It makes me feel twitchy inside...

The other fun thing is that sometimes one function calls another 
function, and the other function returns a char*. So "you" didn't 
allocate anything, but the function you called did, and you need to 
remember to deallocate it. (Arguably that's poor design, but hey, I 
didn't write the code...)

PS. What black magic is it that makes delete[] work correctly?


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.