使用std::vector时发生访问冲突

Access violation when using std::vector

本文关键字:访问冲突 vector std 使用      更新时间:2023-10-16

我得到以下错误:

  • 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)的值。