기존의 코드
class Player{...};
Player* player = player_init("(^___^)", 50, true);
Player* player_init(const char* shape, int pos, boolvisible) {
Player* player = (Player*)malloc(sizeof(Player));
if (player == nullptr) return player;
player->shape = (char*)malloc(sizeof(char) * (strlen(shape) + 1));
if (player->shape != nullptr)
strcpy(player->shape, shape);
player->pos = pos;
player->visible = visible;
return player;
}
void player_deinit(Player* player)
{
if (player == nullptr) return;
free(player->shape);
player->shape = nullptr;
player->pos = 0;
player->visible = false;
free(player);
}
다른 버전의 코드
class Player{...};
Player player
plyaer_init(&&player, ...)
player_init(Player**player) {
if(*player = nullptr) {
*player = (Player*)malloc(sizeof(Plyaer));
*player->heapAllocated = true;
}
*player->pos = 10;
}
player_deinit(Player* player) {
if(player->heapAllocated == true) free(player);
}
포인터 변수에서는 '->' 이전의 변수가 nullptr인지 아닌지 확인이 필요하다.
reference는 nullptr을 확인할 필요가 없다. = 실체를 넘겨주기 때문에 nullptr일 수 없다, 무조건 실체만 넘겨주기 떄문이다.
그러나 포인터 변수는 실체를 보장받을 수 없기에 nullptr인지 확인해야 한다.