简体   繁体   中英

Vector allocation and memory usage

In a mathematical context, I have a class containing a vector of real numbers. This vector can be quite huge, or not. It depend of the user. I see two ways to allocate the memory, but I can't choose. What do you think about these two solutions ?

template <typename T>
T* new_array<T>(unsigned long int size) throw(AllocationFailure);

class MyVector
{
  private:
    unsigned long int datasize;
    double* data;
  public:
    // other member functions
    void allocate1(unsigned long int size);
    void allocate2(unsigned long int size);
};

void MyVector::allocate1(unsigned long int size)
{
  delete [] this->data;
  this->data = 0;
  this->datasize = 0;
  try { this->data = new_array<double>(size); }
  catch(const AllocationFailure& e){ throw AllocationFailure(std::string("Impossible to allocate the vector : ") + e.what()); }
  this->datasize = size;
}

void MyVector::allocate2(unsigned long int size)
{
  double* new_data = 0;
  try { new_data = new_array<double>(size); }
  catch(const AllocationFailure& e){ throw AllocationFailure(std::string("Impossible to allocate the vector : ") + e.what()); }
  delete [] this->data;
  this->data = new_data;
  this->datasize = size;
}

With the first solution, I only use the memory needed, but I loose the content in case of allocation failure. With the second solution my vector is not changed in case of allocation failure but I use a lot of memory I don't realy need at each allocation.

What is the common way to do that in a mathematical context ? Is there still other ways to do that I missed ? Maybe the better solution is keep the two solutions and let the user choose ?

The thing is if you can handle the exception. If you can handle the exception and continue the program you should choose the second, because you can recover after the exception, and you may want the data. If you can't then it's the first one that is the most effective here.

But your code is a quite confusing. It's as if you don't need the previous data after you allocate. (Most of the times you copy the data to the new allocated memory) If it was your intention that the first one all the times, because if you take the risk that you lose the previous data, then it means that further you don't need it anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM