On Thu, 2011-09-08, Paul N wrote:
> On Sep 8, 5:05*pm, Noah Roberts <roberts.n...@gmail.com> wrote:
>> On Sep 8, 8:56*am, Nephi Immortal <immortalne...@gmail.com> wrote:
>> > * * * * I am surprised to find out why the destructor function does not test
>> > pointer before memory is deleted.
>>
>> > struct Object
>> > {
>> > * * * * Object( int n ) : ptr( new char[ n ] )
>> > * * * * {
>> > * * * * }
>>
>> > * * * * ~Object()
>> > * * * * {
>> > * * * * * * * * // comment if condition
>> > * * * * * * * * // if( ptr != NULL )
>> > * * * * * * * * * * * * delete [] ptr;
>> > * * * * }
>>
>> > * * * * char *ptr;
>>
>> > };
>>
>> > * * * * Any C++ books say you must always include if condition to test
>> > pointer if it is not zero before memory is allowed to be deallocated.
>>
>> Throw all your C++ books away then.
>>
>> > * * * * I found out that delete function already has if condition. *The
>> > delete function returns zero without deallocating memory if pointer is
>> > zero.
>>
>> Yep.
>
> Besides, I thought new couldn't return NULL anyway?
A standard new cannot. But there are often other valid reasons 'ptr'
may be null at the time the destructor is called. In the class above,
a single 'obj.ptr = 0' will do.
/Jorgen
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .
|