第二个"if"语句中可能存在逻辑错误?

Ran*_*leb 1 c++

我不明白在这里使用第二个"if"语句.如果"Tptr"已经测试了大于零的"新容量",它怎么能为0?其他一些数字作为"newcapacity"可以使"Tptr"为零吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*cia 5

因为之前的这条线是必要的:

Tptr = new(std::nothrow) T [newcapacity];
Run Code Online (Sandbox Code Playgroud)

以上是无抛出版本,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);
}
Run Code Online (Sandbox Code Playgroud)