2014-10-29 36 views
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; 
} 

第一個解決方案,我只使用所需的內存,但在分配失敗的情況下,我丟失了內容。使用第二種解決方案時,我的向量在分配失敗的情況下不會改變,但是我使用了大量的內存,我並不需要每次分配。

在數學背景下做這件事的常用方法是什麼?還有其他的方法可以做到嗎?也許更好的解決方案是保持兩種解決方案,並讓用戶選擇?

+3

您的第一個方法提供了「基本的異常安全」(也稱爲「無泄漏」)。第二種方法提供了「強大的異常安全性」(也稱爲「回滾」)。你的政策應該是由你決定的。 – 2014-10-29 13:25:39

+1

任何不使用'std :: vector '的理由? – Baldrickk 2014-10-29 13:25:55

+1

@Baldrickk:是的,這裏只是一個小例子。在我的真實代碼中,它不是一個向量,而是一種矩陣,我使用Lapack,所以我需要用指針來管理我的內存。 – Caduchon 2014-10-29 13:28:31

回答

1

事情是,如果你能處理異常。如果你能處理異常並繼續程序,你應該選擇第二個,因爲你可以在異常後恢復,並且你可能需要數據。如果你不能,那麼這是第一個在這裏最有效的方法。

但是你的代碼很混亂。就好像您在分配後不需要以前的數據。 (大多數情況下,您將數據複製到新分配的內存中)如果您的意圖始終是第一個,那麼因爲如果您承擔了丟失之前數據的風險,那麼意味着您還沒有無論如何需要它。