使用std :: vector时访问冲突

Jea*_*ley 0 c++ stdvector

我收到以下错误:

  • 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

完整代码:

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();
};
Run Code Online (Sandbox Code Playgroud)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主要:

#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);

}
Run Code Online (Sandbox Code Playgroud)

请原谅这个混乱,这段代码是从之前的代码中删除的,它们具有相同的错误.

Set*_*gie 5

你是move荷兰国际集团的unique_ptr,使其不再指向new Player,然后你使用它:

world.setPlayer(move(player));

...

player->printInventory();
Run Code Online (Sandbox Code Playgroud)

不要move只用于编译代码; 使用,shared_ptr这样你就可以有多个指向对象的指针.