赋值变量时c++未处理异常访问冲突
c++ unhandled exception access violation at assigning variable
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停止后,现有的向量将仍然指向内存中的某个地方
相关文章:
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 堆栈上的 C++ 访问冲突写入异常
- 引发异常:写访问冲突. temp 为 nullptr
- 在C++中删除双向链表的头节点后出现访问冲突异常
- C++ 引发异常:访问冲突写入
- 未处理的异常..访问冲突写入位置
- 存储类对象的C++模板链表-未处理的异常访问冲突读取位置
- 读取位置/使用结构的矢量时发生未处理的异常访问冲突
- 未处理的异常:访问冲突读取位置
- 未捕获异常.访问冲突读取位置
- 未处理的异常 - 访问冲突读取位置0x00000000
- 使用函数指针C++异常:访问冲突执行位置0x00000000
- 赋值变量时c++未处理异常访问冲突
- 在c++中使用JNI时,c0000005异常(访问冲突)
- c++ std::cin未处理异常:访问冲突写入位置
- 使用 int 变量的 C++ 异常访问冲突
- 未处理的异常/访问冲突,只要我在变量上使用 OutputDebugStringW()
- 异常:访问冲突