Art C Art C - 4 months ago 12
C++ Question

Delete mulitple pointers in a method of another class

I am editing some code of an open source game and normally the code doesn't directly access the player or creature class; however its parameter

Cylinder
is at the top of the food chain when it comes to everything.

My question is should I be deleting all these pointers or setting them to
NULL
after I am done with them?

Here is the code I've written; it works fine but I don't want to crash the server over an issue such as a dangling pointer (still a bit new to 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);
}
}
}

Answer

In general (and unless the documentation says otherwise), don't delete objects if you are passed a pointer. Assume that you are not being given ownership of the object.

Modern C++ helps you avoid needing to know whether you are being given ownership: you may be given a std::shared_ptr<Cylinder> or a std::unique_ptr<Cylinder> - either way, deletion is handled for you when the smart pointer goes out of scope. But often, you have to work with a library that doesn't give you such reassurance.

There's no need to null out any pointers used within a small scope (e.g. a function). If you keep pointer variables around for longer (in a member variable, perhaps), then it may help prevent accidents if you do so. As C++ is not a garbage-collected language, there's no benefit from nulling pointers that are about to go out of scope.

Comments