【问题标题】:Dynamically allocating an array of objects to a pointer using new: "potentially uninitialized pointer"使用 new 将对象数组动态分配给指针:“可能未初始化的指针”
【发布时间】:2017-03-31 03:53:59
【问题描述】:

以下函数必须为对象数据库分配内存,并分配指向对象数组的指针。

然后,指针将使用指针算术循环遍历数组,并根据用户输入将每个对象初始化为正确的值。

这是不起作用的代码:

//**********************************************************************
//*                        Get Database Records                        *
//**********************************************************************
record* get_records_database(int quantity)
{
   record *p_database; // Pointer to the records database
   record *p_record;   // Pointer to each object in the database
   int    index = 1; // Number of objects in the database

   // Allocate a database of object records
   try
   {
      p_database = new record[quantity];
   }
   catch (bad_alloc xa)
   {
      fatal_error(ALLOC_ERR, "get_records_database", 
                             "object records database");
   }

   // Loop processing object records until the database is filled
   // --- //

   // Test:
   p_database->set_amount(400);
   p_database->get_amount();

   return p_database;
}

我面临的问题是在 VisualStudio 中修复以下编译器错误:错误 C4703:使用了可能未初始化的本地指针变量“p_employee_database”。

这是一个项目;需要使用 new、try、catch 和指针;函数的结构是必需的(不是全部写在这一点上);指向类的指针的返回值是必需的。我的老师对他的要求非常严格。

非常感谢您对解决此错误的任何帮助。谢谢;)

【问题讨论】:

  • 什么是fatal_error,为什么你的代码在发生错误时会继续运行,就好像它们没有问题一样?
  • @PaulMcKenzie 致命错误函数打印错误消息并以错误号退出。
  • 从什么退出?程序??
  • @PaulMcKenzie 是的,使用exit();
  • Please don't do that。无论如何,编译器警告是有保证的,因为编译器看到的是它所看到的。您发现了错误,并且该本地块中没有任何内容建议您离开该功能。

标签: c++ pointers dynamic-memory-allocation


【解决方案1】:

您的代码至少有两个问题:

   try
   {
      p_employee_database = new employee_bonus_record[employee_quantity];
   }
   catch (bad_alloc xa)
   {
      fatal_error(EMPLOYEE_ALLOC_ERR, "get_employee_records_database", 
                                      "employee bonus records database");
   }
   //.. rest of code, assuming p_employee_database is ok.

如果抛出异常,p_employee_database 未初始化,但是您无法从函数返回。相反,您的逻辑继续使用p_employee_database,就好像没有任何问题一样,因此会发出编译器警告。

即使如您所说,fatal_error 调用exit(),编译器也看不到这一点。它只查看该代码块并给出警告。如果你想抑制警告,你可以返回nullptr

   try
   {
      p_employee_database = new employee_bonus_record[employee_quantity];
   }
   catch (const bad_alloc& xa)
   {
      fatal_error(EMPLOYEE_ALLOC_ERR, "get_employee_records_database", 
                                      "employee bonus records database");
      return nullptr;
   }

代码的第二个错误是你应该通过常量引用catchstd::bad_alloc,而不是通过值。见this article

【讨论】:

  • 请注意,引用 xa 会发出警告 warning C4101: 'xa': unreferenced local variable。 我将不得不更多地研究@987654332 的一般形式@ 方法来看看为什么这很重要。
  • 可以去掉参数,即(const std::bad_alloc&)。但是,您应该真正记录xa.what() 告诉您的内容。完全忽略系统错误字符串并创建自己的错误解释不是一个好习惯。一个重要的原因是系统错误字符串可以被研究(网络搜索)以找到更多信息,因为系统错误字符串是一致的并且被成千上万的程序员遇到。
  • 只是想感谢您对此代码的建议。当时,离作业到期还有一个晚上,你的帮助是无价的。老师注意到他的要求不正确,第二天就给了我们解决方案,但您允许我按时上交。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2014-03-14
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
相关资源
最近更新 更多