使用 new 将对象数组动态分配给指针:"potentially uninitialized pointer"

Dynamically allocating an array of objects to a pointer using new: "potentially uninitialized pointer"

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

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

这是不起作用的代码:

//**********************************************************************
//*                        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 和指针;函数的结构是必需的(此时还没有全部写好);需要指向 class 的指针的 return 值。我的老师严格按照他的要求严格执行

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

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

   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 未初始化,但是您无法从函数中 return。相反,您的逻辑继续使用 p_employee_database 就好像没有任何问题一样,因此编译器警告。

即使如您所说,fatal_error 调用 exit(),编译器也看不到这一点。它只查看该代码块并发出警告。如果你想抑制警告,你可以 return 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;
   }

代码的第二个错误是您应该 catch std::bad_alloc 通过 const 引用,而不是通过值。参见 this article