c++ - 删除另一个类的方法中的多个指针

标签 c++ pointers dereference

我正在编辑一个开源游戏的一些代码,通常代码不会直接访问玩家或生物类;然而,它的参数 Cylinder 在所有方面都处于食物链的顶端。

我的问题是我应该删除所有这些指针还是在完成它们后将它们设置为 NULL

这是我写的代码;它工作正常,但我不想让服务器因悬垂指针(对 C++ 来说仍然有点新)等问题而崩溃。

bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)
{
    if (cylinder == nullptr) {
        return false;
    }

    if (money == 0) {
        return true;
    }

    if (Creature *creature = cylinder->getCreature()) {
        if (Player *player = creature->getPlayer()) {
            uint64_t cash = player->getBankBalance();
            if (cash < money) {
                return false;
            }
            player->setBankBalance(cash - money);
        }
    }
    return true;
}

void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)
{
    if (Creature *creature = cylinder->getCreature()) {
        if (Player *player = creature->getPlayer()) {
                player->setBankBalance(player->getBankBalance() + money);
        }
    }
}

最佳答案

一般来说(除非文档另有说明),不要 delete对象,如果你传递了一个指针。假设您没有被授予该对象的所有权。

现代 C++ 可帮助您避免需要知道您是否被授予所有权:您可能会获得 std::shared_ptr<Cylinder>std::unique_ptr<Cylinder> - 无论哪种方式,当智能指针超出范围时,都会为您处理删除。但通常情况下,您不得不与无法给您这种保证的图书馆合作。

无需清空在小范围内使用的任何指针(例如函数)。如果您将指针变量保留更长时间(也许在成员变量中),那么这样做可能有助于防止事故发生。由于 C++ 不是垃圾收集语言,因此将即将超出范围的空指针置零没有任何好处。

关于c++ - 删除另一个类的方法中的多个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746113/

相关文章:

c++ - 没有 CCriticalSection 或 CMutex 的锁处理

c++ - 从 vector 访问时,我的可变类的属性没有改变。 (调试)

c++ - 知道 QObject 名称是否已更改的最佳方法是什么

c++ - 如何在cpp中访问 parent 的运营商

C、无法通过取消引用检索变量值,未知段错误

c - typedef 函数指针类型

c - C中解析指针参数

comp.lang.c 常见问题解答 : Function that can return a pointer to a function of the same type

c++ - 最令人烦恼的解析和指针间接/解引用

arrays - 如何在 perl 中用现有数组声明数组?