-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion_4.cpp
50 lines (42 loc) · 1.37 KB
/
question_4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Answer
// When memory is allocated with 'new' it is crucial to delete it when it is no longer needed.
void Game::addItemToPlayer(const std::string& recipient, uint16_t itemId)
{
Player* player = g_game.getPlayerByName(recipient);
if (!player) {
player = new Player(nullptr);
if (!IOLoginData::loadPlayerByName(player, recipient)) {
delete player; // Deallocate memory if loading fails
return;
}
}
Item* item = Item::CreateItem(itemId);
if (!item) {
delete player; // Deallocate memory if item creation fails and player is online
return;
}
g_game.internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT);
if (player->isOffline()) {
IOLoginData::savePlayer(player);
delete player; // Deallocate memory if player is offline after item addition
}
}
// Question
void Game::addItemToPlayer(const std::string& recipient, uint16_t itemId)
{
Player* player = g_game.getPlayerByName(recipient);
if (!player) {
player = new Player(nullptr);
if (!IOLoginData::loadPlayerByName(player, recipient)) {
return;
}
}
Item* item = Item::CreateItem(itemId);
if (!item) {
return;
}
g_game.internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT);
if (player->isOffline()) {
IOLoginData::savePlayer(player);
}
}