我正在使用C++和Allegro進行一個簡單的遊戲。我遇到一個Access violation
運行時錯誤,其中包含unique_ptrs
到ALLEGRO_BITMAPs
的vector
的structs
。複製包含unique_ptrs的結構向量
這是我的結構聲明。
struct Skin {
std::unique_ptr<ALLEGRO_BITMAP> img;
Skin();
Skin(ALLEGRO_BITMAP*);
Skin& operator=(const Skin& s);
Skin(const Skin& s);
};
這裏是另一個文件中構造函數的定義。
Skin::Skin() {
img.reset();
}
Skin::Skin(ALLEGRO_BITMAP* bitmap) {
img.reset(bitmap);
}
Skin::Skin(const Skin& s) {
img.reset(s.img.get());
}
Skin& Skin::operator=(const Skin& s) {
img.reset(s.img.get());
return *this;
}
這是在我的訪問衝突之前被調用的代碼。
generateBase(world, display.get());
其中調用此函數。
void generateBase(World& world, ALLEGRO_DISPLAY* display) {
int x = TILESIZE - WIDTH;
int y = HEIGHT - TILESIZE;
int groundWidth = 3 * WIDTH - 2 * TILESIZE;
Point min{ x, y };
Point max{ x + groundWidth, y + (int)TILESIZE };
ALLEGRO_BITMAP* black = al_create_bitmap(groundWidth, TILESIZE);
ALLEGRO_BITMAP* white = al_create_bitmap(groundWidth, TILESIZE);
al_set_target_bitmap(black);
al_clear_to_color(al_map_rgb(0, 0, 0));
al_set_target_bitmap(white);
al_clear_to_color(al_map_rgb(255, 255, 255));
al_set_target_bitmap(al_get_backbuffer(display));
std::cout << "Errors incoming!" << endl;
createPlayer(world, x, y, 0, 0, 5, vector <AABB> { AABB(min, max) }, vector <Skin> { Skin(black), Skin(white) });
std::cout << "Did we make it?" << endl;
}
反過來調用這個函數。
unsigned int createPlayer(World& world, int x, int y, float dx, float dy, float speed, vector<AABB>& mesh, vector<Skin>& imgs) {
unsigned int entity = newEntityIndex(world);
world.masks[entity].set(COMPONENT_TYPE);
world.masks[entity].set(COMPONENT_POINT);
world.masks[entity].set(COMPONENT_UNITVECTOR);
world.masks[entity].set(COMPONENT_SPEED);
world.masks[entity].set(COMPONENT_COLLISIONMESH);
world.masks[entity].set(COMPONENT_SKINLIST);
world.types[entity] = TYPE_PLAYER;
world.points[entity] = Point(x, y);
world.unitVectors[entity] = UnitVector(dx, dy);
world.speeds[entity] = Speed(speed);
world.collisionMeshes[entity].mesh = mesh;
cout << "Starting vector copy" << endl;
for (auto skin : imgs) {
world.skinLists[entity].imgs.push_back(move(skin));
}
cout << "Ending vector copy" << endl;
return entity;
}
這是我的deleter for unique_ptr。
namespace std {
template<>
class default_delete <ALLEGRO_BITMAP> {
public:
void operator()(ALLEGRO_BITMAP* ptr) {
cout << ptr << endl;
al_destroy_bitmap(ptr);
}
};
}
這裏是輸出。
Errors incoming!
Starting vector copy
00AF9468
00AF9468
當我修改我的generateBase
createPlayer
呼叫通過去除Skin(white)
,輸出改爲。
Errors incoming!
Starting vector copy
00799468
Ending vector copy
00799468
輸出的變化讓我有點疑惑,但我最大的問題是什麼,我需要改變我是如何複製我的unique_ptrs
structs
vector
所以我不嘗試刪除相同的指針兩次。
在此先感謝!
1)你已經被告知[最小的完整的例子(http://stackoverflow.com/help/mcve),2)你的'Skin :: operator ='違反了'std :: unique_ptr'的規則。 – Beta