I am creating a game and i have to destroy player when it collides with an enemy. But the player is a stack object. So must i create a player in heap in order to destroy it (with delete)?
e.g:
Player player(some_initialization);
if (some_condition)
player = Player(); //default constructor gives a "null" object
Conceptually, destructing the Player and nothing else is strange. Normally the Player should have the same lifetime as the Game. If there's no player, why is the game running?
In that case it's not like there's no player, in the sense of faction. There's a player character that's being controlled by the computer. IMO that should be modelled as a Player where the input is coming from someplace other than the human.
.. ?
any stl container can destroy an object, though vectors are a bit clunky about it. Put all players in a list or something and kill them as needed?
you can also bracket it for destruction if for some unconvincing reason it needs to be on the stack:
{
player x;
while (x.isalive())
{
stuffs;
}
} //goodbye x, it exists no more.
whether this makes any sense at all in your program or not is another story. Careful use of threading inside its lifespan brackets could make this design work, but its not terribly good code or a great approach. The only time I have ever done this was to rid myself of some very large intermediate objects that were hogging memory, though we do it all the time in for loops for the loop variable and small things like that (rarely objects).
Which means this should have been obvious as well:
for(object x ; !x.collide();)
{
stuffs.
} //x goes away here too.
Keep in mind that I don't judge too much. This is a case of just because you can do something does not make it good code. Its hard to make this clean, because you probably don't want you main thread stuck in a loop dealing with this, and a big loop around everything is also yucky, so the applications of this are reduced greatly by what you can sensibly put inside one pair of {} and still have a good program.
If constructs like if( this_player.is_alive() ) { /* then do something with this_player */ }
would be scattered throughout the code,
a stylised way of making the code look much neater is by using zombie objects (aka null objects). https://sourcemaking.com/design_patterns/null_object