【问题标题】:values in class destroyed when getting back to main function c++返回主函数c ++时类中的值被破坏
【发布时间】:2016-12-10 17:28:41
【问题描述】:

我的 C++ 代码有问题。 我有一个正在使用的 DataStructure 类,特别是它的 GetAllCreaturesByLevel 方法定义如下:

Class DataStructure;
StatusType DataStructure::GetAllCreaturesByLevel(int magiID, int **creatures, int *numOfCreatures);

此方法从主函数接收指针,并返回有关它正在处理的对象的一些统计信息。

要在主函数中使用此方法,我调用一个函数,该函数将从主函数传递指针,将对象从 void* 转换为 DataStructure* 并调用其方法 GetAllCreaturesByLevel。该函数定义如下:

 StatusType GetAllCreaturesByLevel(void *DS, int magiID, int **creatures, int *numOfCreatures){
     if((DS == NULL)||(creatures == NULL)||(magiID == 0)||(numOfCreatures == NULL)){
        return INVALID_INPUT;
      }
    return ((DataStructure*)DS)->GetAllCreaturesByLevel(magiID, creatures, numOfCreatures);
}

代码在此函数中完美运行。问题是当回到主时:指针返回正确的值,但对象中的所有数据都被更改并变成垃圾值。

这个错误的原因是什么?

【问题讨论】:

  • 哪个对象被销毁了? DatStructure 类型之一或 StatusType 类型之一?
  • 被销毁的对象是 DataStructure* 之一(作为 void* 传递)。 StatusType 只是一个枚举,提供有关函数的最终问题(成功、失败、分配错误)的一些信息。奇怪的是 Destructor 似乎没有被使用。
  • 为什么在 C++ 中使用 void 指针和 ** 数组?如果您实际上是在使用 C 进行编程,则需要按值传递,或遵循您希望更改的那些值。就目前而言,这个函数试图改变 main 范围之外的值,而原始的垃圾值仍然存在,因为它们从未改变过。

标签: c++ class data-structures destructor


【解决方案1】:

在我使用的方法中:

 int *creaturesArray = new int[*numOfCreatures];

并在生物数组中输入值:

for(int i = 0; i < *numOfCreatures; i++) {
     creatures[i] = &creaturesArray[i];
}

问题出在汇编中。在从 GetAllCreaturesByLevel 返回到 main 时,堆栈比进入函数时更大,因此 DS 在堆栈中的位置与之前不同。因此,放入 DS 的值不是实际值,而是生物数组中的地址之一。

解决办法是:

 int *creatures = new int[*numOfCreatures];

并按原样返回生物,而无需在途中使用另一个数组。

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 2020-02-17
    • 2019-04-09
    • 2011-06-26
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多