What is the point of dynamic allocation in C++?
        Posted  
        
            by 
                Aerovistae
            
        on Programmers
        
        See other posts from Programmers
        
            or by Aerovistae
        
        
        
        Published on 2012-06-09T17:08:49Z
        Indexed on 
            2012/06/09
            22:46 UTC
        
        
        Read the original article
        Hit count: 377
        
I really have never understood it at all. I can do it, but I just don't get why I would want to.
For instance, I was programming a game yesterday, and I set up an array of pointers to dynamically allocated little enemies in the game, then passed it to a function which updates their positions.
When I ran the game, I got one of those nondescript assertion errors, something about a memory block not existing, I don't know. It was a run-time error, so it didn't say where the problem was. So I just said screw it and rewrote it with static instantiation, i.e.:
while(n<4)
{
Enemy tempEnemy = Enemy(3, 4);
enemyVector.push_back(tempEnemy);
n++;
}
updatePositions(&enemyVector);
And it immediately worked perfectly.
Now sure, some of you may be thinking something to the effect of "Maybe if you knew what you were doing," or perhaps "n00b can't use pointers L0L," but frankly, you really can't deny that they make things way overcomplicated, hence most modern languages have done away with them entirely.
But please-- someone -- What IS the point of dynamic allocation? What advantage does it afford? Why would I ever not do what I just did in the above example?
© Programmers or respective owner