C++ 交换 unique_ptr's

标签 c++ smart-pointers unique-ptr

刚接触这类东西,可能做错了什么,但是-

我有 3 个成员

std::unique_ptr<Gun> currentWeapon;
std::unique_ptr<Gun> weaponSlotOne;
std::unique_ptr<Gun> weaponSlotTwo;

Gun 是一个基类,它具有其他派生类,例如 PistolSMG

我正在做的是将 weaponSlotOneweaponSlotTwo 设置为两把不同的枪,然后将 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/

相关文章:

c++ - 为什么为 x64 平台编译的 C++ 程序比为 x86 平台编译的慢?

c++ - 在 C++ 中记录动态数据

c++ - 随机数生成

c++ - 仅对类 NOT STATIC 的每个对象调用方法一次

c++ - 如何将 unique_ptr 移动到原始指针?

c++ - 具有 unique_ptr 和线程的默认 vector 构造函数

c++ - 转换多态智能指针对象

c++ - 智能指针 : cast between base and derived classes

c++ - unique_ptr<TStringList []> dsts(new TStringList[5]) 失败

c++ - unique_ptr 的临时只读拷贝