[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: 19981022: deletes in C++ netcdf interface?



Dr. Bristow,

> To: "Unidata Technical Support" <address@hidden>
> From: "Dr Paul A Bristow" <address@hidden>
> Subject: deletes in C++ netcdf interface?
> Organization: hetp Chromatography
> Keywords: 199810220827.CAA01119

In the above message, you wrote:

> Please can you explain why there are deletes in the following bit of code
> cut from nctst.cc
> 
> void DumpableNcFile::dumpgatts( void )
> {
>     NcAtt *ap;
>     for(int n = 0; ap = get_att(n); n++) {
>       cout << "\t\t" << ":" << ap->name() << " = " ;
>       NcValues *vals = ap->values();
>      cout << *vals << " ;" << endl ;
>      delete vals;
>      delete ap;
>     }
> }

The objects pointed to by the return values of "get_att()" and
"values()" belong to the caller: they are created by the called
function but responsibility for them passes to the caller upon return.
You are correct in that at the end of the block, the variables "ap" and
"vals" will be destroyed; the objects they point to, however, will not
be destroyed and so must be explicitly destroyed by the caller.  Failure
to do this will result in the infamous C++ memory leak problem in which
allocated objects have had all pointers to them destroyed.

The contract for the "get_att()" can be found at URL

    http://www.unidata.ucar.edu/packages/netcdf/cxxdoc.html#SEC11

and the contract for the "values()" function can be found at URL

    http://www.unidata.ucar.edu/packages/netcdf/cxxdoc.html#SEC13

Unfortunately, the documentation on the "values()" function isn't as
clear on the passing of ownership as the documentation on "get_att()".

> It seems to me that ap is a pointer to NcAtt and is a local variable on the
> stack, and will be destroyed when the function exits.

On exit from the block, the variable "ap" will be destroyed but not what
it points to.

> Doesn't delete remove objects from the heap, not the stack? (Balancing a new
> somewhere).

This is correct.

> It seems to work just as well without (but perhaps there is a memory leak
> which these deletes avoid?)

This is correct.

--------
Steve Emmerson   <http://www.unidata.ucar.edu>