2014-01-18 49 views
1

我不明白在這裏使用第二個「if」語句。如果它已經測試了一個大於零的「新容量」,那麼「Tptr」如何爲0?可以將其他一些數字作爲「新容量」使「Tptr」爲零嗎?第二個「if」語句中可能的邏輯錯誤?

template <typename T> 
T* Vector<T>::NewArray(size_t newcapacity) 
// safe memory allocator 
{ 
    T* Tptr; 
    if (newcapacity > 0) 
    { 
     Tptr = new(std::nothrow) T [newcapacity]; 
     if (Tptr == 0) 
     { 
     std::cerr << "** Vector error: unable to allocate memory for array!\n"; 
     exit (EXIT_FAILURE); 
     } 
    } 
    else 
    { 
     Tptr = 0; 
    } 
    return Tptr; 
} 
+2

打印出的錯誤信息是否使原因清楚? – Barmar

+2

@Barmar:我猜RandomPleb可能認爲錯誤信息是毫無意義的。我肯定遇到過檢查從空常返回的'null'指針的代碼,拋出'new'。沒有多少文本甚至提到'nothrow''new',所以我認爲OP不理解其意義是可以理解的。正如另一個評論指出的那樣,在使用'new'之後檢查null的C++ FAQ條目從來沒有提到'nothrow',並且幾乎絕對地聲明瞭你永遠不需要檢查null,唯一的例外是關於過時的編譯器。 –

回答

5

這是因爲該行之前的必要:

Tptr = new(std::nothrow) T [newcapacity]; 

以上是分配失敗時返回空指針的no-throw version of new[]。因此下一行必然意味着它正在檢查new[]分配是否失敗。

if (Tptr == 0) // Check if allocation failed 
{ 
    // Allocation has failed 
    std::cerr << "** Vector error: unable to allocate memory for array!\n"; 
    exit (EXIT_FAILURE); 
} 
+0

現在有道理。謝謝。 – RandomPleb

2

當機器運行的內存,你要求它不要把它返回nullptr具有價值異常0

-1

如果新返回NULL會怎麼樣。在使用mallocnew後,您應該始終檢查爲空。

+1

如果新投擲? – neagoegab

+0

@neagoegab我們可以使用std :: set_new_handler來處理它嗎? –

+0

如何應對「你應該總是無效檢查」? – neagoegab