c++ - Safe array deletion -


i'm new c++ , i'm not absolutely sure how deal arrays , pointers in safe way. in class got member called items:

item * items; 

in class method called read() open file , read items file. allocate space accordingly:

items = new item[item_count]; 

item_count given variable in file , read in advance before creating items. in deconstructor in class release memory again:

delete[] items; 

but if call method read() twice before deconstructor executed memory first array not released properly. release in read method in advance before allocating new memory. how check if memory allocated array items?

edit: know there many other possibilities out there more 'modern' approachs , more comfortable solutions. in case explicitly told use pointers , arrays (education purpose only).

in c, initialize pointer null can check whether or not points valid memory, , after deallocation set null.

failing so, may cause problems, dereferencing deallocated pointer (they're called dangling pointers), must careful.

in c++ should use nullptr equivalent c's null.

also, there smart pointers in c++, i.e. pointers can automatically.

edit: (the answer above edited) suggested comments, , although same idea correct, should not use null in c++, instead use nullptr has same functionality, takes care fact in c++ void * not automatically converted other pointer type in c.

this stack overflow answer has details, , example definitevely convince , me use nullptr instead.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -