1
在数学上下文中,我有一个包含实数向量的类。这个矢量可能相当大,或者不是。它取决于用户。我看到两种分配内存的方式,但我不能选择。您如何看待这两种解决方案?向量分配和内存使用
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;
}
第一个解决方案,我只使用所需的内存,但在分配失败的情况下,我丢失了内容。使用第二种解决方案时,我的向量在分配失败的情况下不会改变,但是我使用了大量的内存,我并不需要每次分配。
在数学背景下做这件事的常用方法是什么?还有其他的方法可以做到吗?也许更好的解决方案是保持两种解决方案,并让用户选择?
您的第一个方法提供了“基本的异常安全”(也称为“无泄漏”)。第二种方法提供了“强大的异常安全性”(也称为“回滚”)。你的政策应该是由你决定的。 – 2014-10-29 13:25:39
任何不使用'std :: vector'的理由? –
Baldrickk
2014-10-29 13:25:55
@Baldrickk:是的,这里只是一个小例子。在我的真实代码中,它不是一个向量,而是一种矩阵,我使用Lapack,所以我需要用指针来管理我的内存。 – Caduchon 2014-10-29 13:28:31