I want to create a vector of data, but I want to both set it’s size and fill its elements in a sub-function. Is this an appropriate time to use the new operator? Is there a better way to do it? It seems like an appropriate time, but I’m hesitant because of Why should C++ programmers minimize use of 'new'?
int main()
{
vector<double> *array1;
vector<double> *array2;
OtherArgs otherArgs;
FillArrays(array1,array2,otherArgs);
//Do other stuff
delete array1;
delete array2;
}
void FillArrays(vector<double> *&array1, vector<double> *&array2, OtherArgs &otherArgs)
{
int size=GetSize(otherArgs);
array1 = new vector<double>(size);
array2 = new vector<double>(size);
//Other code to fill the arrays
}
Thank you
Here are a couple of reasons why the original sample is troublesome
deletecalls aren’t protectedFillArraysis passed a non-NULLvectory<double>value it will leak memory because it didn’t delete the previous value. It couldn’t reliably calldeleteeven if it wanted to because the value may have been stack allocated.The easiest way to do this is to just declare the values on the stack and pass them by reference that way.
The
vector<T>will initialize themselves to an empty list when declared in this manner. TheFillArraysmethod can then populate them as necessary.