resize dynamic memory problem

I want to implement the class FloatArray's resize function
1
2
3
4
5
6
7
class FloatArray {
private:
    float * mDate;
    int mSize;
public:
    void resize(int newSize);
}


Is this right??
I wonder whether I need to use the delete[], but I can't find out when or whether use this;

1
2
3
4
5
6
7
8
9
10
11
void FloatArray::resize(int newSize) {
	mData = new float[newSize];
	if(newSize >= mSize) {
		// copy old elements to new array
	    for(int i = 0; i < mSize; i++)
		newArray[i] = mData[i];
	} else {	// new array is a lesser size than old array
	    for(int i = 0; i < newSize; i++)
		newArray[i] = mData[i];
	}
}
closed account (DSLq5Di1)
I wonder whether I need to use the delete[]
Yes!

This mData = new float[newSize]; is a memory leak, any previously allocated memory pointed to by mData is lost until the application exits.

1
2
3
4
5
6
7
8
9
10
	if (newSize > 0) // sanity check, I would also avoid resizing if the new size is less than or equal to mSize.
	{
		float * newArray = new float[newSize]
		// copy old elements to new array
		...

		delete[] mData; // delete the old array
		mData = newArray; // assign the pointer to the new array
		mSize = newSize;
	}
Last edited on
but if my FloatArray object have some values ,when I use the resize function, I want to copy the value to my newsize, what should I do?( I don't know where to use the delete [] .)
Topic archived. No new replies allowed.