Henrietta Denoue wrote:
Hi
I am new to C++ and suffering from dynamic allocation.
I have a function that returns an integer pointer and
want to assign this to another pointer:
class cssReader
{
public:
cssReader();
cssReader(string, string);
~cssReader();
What does the destructor do?
Does it delete[] the allocated memory?
int *data;
ccReader *css = new cssReader;
void getData()
{
...
...
data = css->GetWandRead(dirname, rows);
// plot data
delete [] data;
That's not a good idea.
You should get into the habit of:
"The object (or function) that allocated the data is
reponsible for freeing it."
That's a simple rule and there are exceptions to it, but as a rule
of thumb it works pretty well. In your example it means, since the
cssReader object allocated the memory, it is responsible for deleting
it. Not the code that created the cssReader object, not some obscure
function, nothing else but the cssReader object itself. If you keep
the code environment dealing with managing that memory small, it is much
easier to find bugs and code correctly as if some function allocates some
memory and 15000 lines of code later in some other function the deallocation
happens.
--
Karl Heinz Buchegger
kb******@gascad.at