2014-01-18 54 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