赋值变量时c++未处理异常访问冲突

c++ unhandled exception access violation at assigning variable

本文关键字:异常 访问冲突 未处理 c++ 变量 赋值      更新时间:2023-10-16
std::vector <Item*> itemSlot;
itemSlot.resize(1);
Item testItem;
testItem.item_id = 99;
*itemSlot[0] = testItem;        // ERROR
std::cout << "ID: " << itemSlot[0]->item_id << std::endl;

为什么我得到一个错误?

我知道我可以这样做:

itemSlot[0] = &testItem;

但是我不想这样做,因为如果我在函数中创建项目并在函数中分配它,如果我在函数外调用itemSlot[0]->item_id,它会给我一个随机数,因为变量item会被销毁,指针会指向什么

的含义
*itemSlot[0] = testItem; // Copy-assign testItem into the item at index zero

完全不同
itemSlot[0] = &testItem; // Place the address of testItem at index zero

如果索引0处有一个Item,第一个结构可以工作,但是你没有:对itemSlot.resize(1)的调用将nullptr置于索引0,因此解引用它会导致未定义的行为。

有几个可用的解决方案:

  • 让你的vector成为Item的矢量而不是Item*,或者
  • 使用Item *testItem = new Item(),最后呼叫delete,或
  • 使用new Item()和一个智能指针向量来避免手动删除。

您已经获得了指向项目的指针向量。这样做通常是个坏主意。共享指针会更好。如果你想使用指针,那么你应该为它们分配内存,所以你应该这样做:

itemSlot[0] = new Item;

,然后再访问。更好看的是:

Item* tmpItem = new Item;
itemSlot.push_back(tmpItem);

之后不要忘记释放内存。使用共享指针或唯一指针代替


的另一种方法:

itemSlot[0] = &testItem;

这也是可以的,但是在testtem停止后,现有的向量将仍然指向内存中的某个地方