C++ 使用std::vector时发生访问冲突
我得到以下错误:C++ 使用std::vector时发生访问冲突,c++,stdvector,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<<
- TBG.exe中0x012a4bd9处的未处理异常:0xC0000005:访问冲突读取位置0x0000002c
void Player::printInventory(){
if(inventory.size() != 0){
for(unsigned int i=0; i<inventory.size(); i++){
cout<<inventory[i] << endl;
}
}
}
void播放器::printInventory(){
如果(inventory.size()!=0){
对于(unsigned int i=0;i使用!inventory.empty()代替inventory.size()!=0)。
因此,对于代码,当您移动unique_ptr时,unique_ptr将被释放,因此它将指向零。使用!inventory.empty()代替inventory.size()!=0。
因此,对于代码,当您移动unique_ptr时,unique_ptr将被释放,因此它将指向零。您正在移动unique_ptr
,以便它不再指向新播放器,然后您正在使用它:
world.setPlayer(move(player));
...
player->printInventory();
不要只使用move
来编译代码;使用shared\u ptr
可以有多个指向该对象的指针。您正在移动唯一的\u ptr
,这样它就不再指向新玩家,然后您正在使用它:
world.setPlayer(move(player));
...
player->printInventory();
不要只使用move
来编译代码;使用shared\u ptr
这样你就可以有多个指向该对象的指针。看起来你在使用某个空对象。在崩溃之前在函数中打印该(播放器)的值。看起来你在使用某个空对象。打印该(播放器)的值在崩溃前的函数中。可以包含更多上下文吗?编译并包含库存声明的代码段最好。需要更多上下文。请使用上下文。我认为播放器可能分配不正确。可以包含更多上下文吗?编译并包含decl的代码段库存的配置最好。需要更多的上下文。请使用上下文。我认为播放器
可能分配不正确。好的,我现在发布播放器类库存。大小()!=0
很好。问题一定在别处。@EitanT是的,但是使用inventory.empty()对于检测向量为空,比inventory.size()==0更好,在这个代码条件下是不必要的。@永远的,为什么确切地说它更好?无论如何,我认为这应该是一个注释,而不是一个答案。好的,我现在发布播放器类inventory.size()!=0
很好。问题一定在别处。@EitanT是的,但使用inventory.empty()来检测向量是否为空比inventory.size()==0更好,并且在这种代码条件下是不必要的。@永远的,为什么确切地说它更好?无论如何,我认为这应该是一个注释,而不是答案。
#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);
}
world.setPlayer(move(player));
...
player->printInventory();