Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

De-allocating a variable using "delete"

Status
Not open for further replies.

MattWoberts

Programmer
Oct 12, 2001
156
GB
Hi,

I think this is a simple question - I just can't find any reesources to help me.

I have an array called i, in my class. I need to de-allocate using delete, but only if it has been allocated in the first place (it may not be allocated in the classes life).

My class destructor is pretty simple:

CInterval::~CInterval()
{
delete [] i;
}

I thought this would work:

CInterval::~CInterval()
{
if )i != null)
delete [] i;
}

But, it doesn't!

Any ideas?

 
Well, it depends on a type of your array.
If it is a pointer to a simple type (such as int, char etc.) you should write

delete i;

If it is a static array such as

int i[10];

you don't have to delete it at all.

I can assume that the same works when your i is an array of complex classes (having their own destructors), i.e. you don't need to delete them manually.
However, I'm not very sure with the last case.

Hope that'll help.

 
It all makes sense, but my particular problem is that my array is dynamically allcoated with the new operator.

The problem is: the array allocation may never occur, so hwo do I first check that there is anything to deallocate (delete) before I delete it?

Thanks
 
Assign initial value NULL to that pointer in constructor.
 
Actually if it is set to NULL it is perfectly legal to delete it ONE time.


class foo{
char* buf;
public:
foo() : buf(NULL){}
~foo(){ delete [] buf; }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top