刚接触这类东西,可能做错了什么,但是-
我有 3 个成员
std::unique_ptr<Gun> currentWeapon;
std::unique_ptr<Gun> weaponSlotOne;
std::unique_ptr<Gun> weaponSlotTwo;
Gun 是一个基类,它具有其他派生类,例如 Pistol
和 SMG
。
我正在做的是将 weaponSlotOne
和 weaponSlotTwo
设置为两把不同的枪,然后将 currentWeapon
设置为第一把武器。
weaponSlotOne.reset(new DevPistol());
weaponSlotTwo.reset(new AutoDevPistol());
currentWeapon = std::move(weaponSlotOne);
我有一个 switchWeapons
方法,它是这样做的:
void Player::switchWeapons() {
if(currentWeapon == weaponSlotOne) {
currentWeapon = std::move(weaponSlotTwo);
}
else {
currentWeapon = std::move(weaponSlotOne);
}
}
这似乎出于某种原因销毁/取消分配了两把枪。我不太确定出了什么问题。
最佳答案
问题是在对象上调用 std::move
后,该对象处于不确定状态,除了销毁它或分配给它之外,您不能安全地对该对象做任何事情
在你的例子中,在执行 currentWeapon = std::move(weaponSlotOne);
之后,weaponSlotOne
是不确定的,所以当你测试 currentWeapon == weaponSlotOne
你可能会得到任何结果。这可能是错误的(weaponSlotOne
将为 null),因此您只需将其复制到 currentWeapon
,丢弃那里的任何内容(删除它)。
问题是,你想做什么?如果您想要两件武器,并且想跟踪哪一件是最新的,那么这样做可能更有意义:
std::unique_ptr<Gun> *currentWeapon;
std::unique_ptr<Gun> weaponSlotOne;
std::unique_ptr<Gun> weaponSlotTwo;
weaponSlotOne.reset(new DevPistol());
weaponSlotTwo.reset(new AutoDevPistol());
currentWeapon = &weaponSlotOne;
void Player::switchWeapons() {
if(currentWeapon == &weaponSlotOne) {
currentWeapon = &weaponSlotTwo;
}
else {
currentWeapon = &weaponSlotOne;
}
}
或者更简单:
std::unique_ptr<Gun> weaponSlot[2];
int currentWeapon = 0;
void Player::switchWeapons() {
currentWeapon ^= 1;
}
关于C++ 交换 unique_ptr's,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27117472/