Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe array deletion

Tags:

c++

arrays

I'm new to C++ and i'm not absolutely sure how to deal with arrays and pointers in a safe way. In my class I got a member called items:

Item * items;

in my class method called read() I open a file and read the items from this file. I allocate the space accordingly:

items = new Item[item_count];

item_count is given as a variable in the file and is read in advance before creating any items. In the deconstructor in my class I release the memory like this again:

delete[] items;

But if i call the method read() twice before my deconstructor is executed the memory for the first array will not be released properly. I would like to release it in the read method in advance before allocating new memory. But how do I check if some memory is already allocated for the array items?

EDIT: I know there are many other possibilities out there with more 'modern' approachs and more comfortable solutions. But in this case we where explicitly told to use pointers and arrays (education purpose only).

like image 991
little_planet Avatar asked Jun 25 '15 15:06

little_planet


People also ask

What happens when you delete an array?

This procedure deletes: All the logical drives on the array. All data on the logical drives that are part of the array.

What is a safe array?

SAFEARRAY is a data-structure used in COM/DCOM to hold additional metadata header of the array along with the payload buffer. SAFEARRAY is generic structure to hold the payload of the array and the element count, dimensions and data type of the elements.

Can you use Delete on an array?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression.


2 Answers

In modern C++, "the safe way" is to avoid raw pointers and raw arrays entirely.

Declare your variable like this:

std::vector<Item> items;

Allocate the space like this:

items.resize(item_count);

In the deconstructor in your class, no code is necessary to release this memory. It's handled automatically.

The reuse of items that you describe in your question will work.

like image 132
Drew Dormann Avatar answered Oct 05 '22 23:10

Drew Dormann


Unless you have some strong reason not to do so, just use std::vector for arrays in C++:

#include <vector>  // for std::vector

....
std::vector<Item> items;

In this way, you don't have to explicitly call delete[] to release vector items' resources; it's just done automatically thanks to vector's (and Items') destructors.

This helps building code that is structurally incapable of leaking resources.


You can create a vector of itemCount Items using something like:

std::vector<Item> items(itemCount);

or you could dynamically resize the vector using its resize() method, e.g.:

items.resize(itemCount);
like image 40
Mr.C64 Avatar answered Oct 06 '22 01:10

Mr.C64