使用std::vector时发生访问冲突
Access violation when using std::vector
我得到以下错误:
- TBG.exe中0x012a4bd9处未处理的异常:0xC0000005:读取位置0x0000002c时发生访问冲突
指向vector.h的size()方法。使用此方法时似乎会发生这种情况:
void Player::printInventory(){
if(inventory.size() != 0){
for(unsigned int i=0; i<inventory.size(); i++){
cout<<inventory[i] << endl;
}
}
}
完整代码:
Player.h:
#pragma once
#include <vector>
#include <memory>
using namespace std;
class Player
{
private:
int health;
string name;
vector<int> inventory;
public:
Player(void);
Player(string);
~Player(void);
void changeHealth(int);
void addToInventory(int);
void removeFromInventory(int);
void printInventory();
};
Player.cpp:
#include "Player.h"
#include <iostream>
#include <string.h>
Player::Player(void)
{
health = 20;
}
Player::Player(string newName)
{
name = newName;
health = 20;
}
Player::~Player(void)
{
}
void Player::changeHealth(int amount){
health += amount;
}
/*void Player::addToInventory(int item){
inventory.push_back(item);
}
void Player::removeFromInventory(int itemID){
for(unsigned int i=0; i<inventory.size(); i++){
if(inventory[i] == itemID)
inventory.erase(inventory.begin()+i);
}
}*/
void Player::printInventory(){
if(!inventory.empty()){
for(unsigned int i=0; i<inventory.size(); i++){
cout<<inventory[i] << endl;
}
}
}
main:
#include "World.h"
#include "Player.h"
#include <iostream>
#include <memory>
World world;
void main(){
unique_ptr<Player> player(new Player("Ted"));
world.setPlayer(move(player));
int selection = 0, inventoryOption = 0, exitOption = 0;
do{
inventoryOption = 0;
exitOption = inventoryOption + 1;
cout<< inventoryOption <<". View Inventory"<<endl;
cout<< exitOption <<". Quit game";
cin>>selection;
if(selection == inventoryOption){
player->printInventory();
}
else{
}
}while(selection != exitOption);
}
请原谅这种混乱,这段代码是从以前有同样错误的代码中删除的。
您正在move
调用unique_ptr
,使其不再指向new Player
,然后使用它:
world.setPlayer(move(player));
...
player->printInventory();
不要仅仅为了编译代码而使用move
;使用shared_ptr
,这样就可以有多个指向对象的指针。
使用!inventory.empty()改为inventory.size()!=0因此,对于代码,当您移动unique_ptr时,unique_pr将被释放,因此它将指向零。
看起来您正在使用一些null对象。在崩溃前在函数中打印this(Player)的值。
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 使用静态 std::vector 类成员时出现访问冲突
- Vector::p ush_back() 给出读取访问冲突
- 调用std::vector::empty()时内存访问冲突读取位置
- 使用XMMatrix和std::vector的访问冲突
- 循环中的 BadPtr 访问冲突,将字符**转换为 std::vector<string>
- 创建具有自动存储的自定义对象并推送回 std::vector 时访问冲突
- 使用std::vector时发生访问冲突
- std::vector push_back 会导致访问冲突
- 处理vector迭代中的访问冲突异常
- c++ Vector读访问冲突Mylast返回0x8
- 给map vector容器的元素赋值时发生访问冲突