🐧Memory Painpoints
Fundamentally, ownership answers the question:
Who is responsible for cleaning up this piece of memory?
As we've seen earlier, memory can be allocated on two distinct regions (i.e the stack and the heap)
Stack
When variables are allocated on the stack, there's no burden on us to deallocate the memory. C++ handles it for us automatically!
int main() {
int x = 10;
} // x is automatically destroyed by end of this scopeHeap
Exercise
I tried my best to write a code snippet to simulate a game I had in mind. Unfortunately, the code doesn't seem to work for some reason. Do you mind helping me find out where the error(s) are ?
#include <iostream>
int* spawnScoreBonus() {
return new int(100);
}
int* generatePlayerHealth() {
int* health = new int(50);
delete health;
return health;
}
int main() {
int* score = spawnScoreBonus();
std::cout << "Player gained score: " << *score << std::endl;
int* health = generatePlayerHealth();
std::cout << "Player health: " << *health << std::endl;
int* enemyHp = new int(200);
int* archerTarget = enemyHp;
int* knightTarget = enemyHp;
delete knightTarget;
delete archerTarget;
return 0;
}As we have seen earlier, even in a small piece of code, there can be many subtle memory issues. Imagine how many of such bugs exist in larger codebases!
To tackle this, modern C++ (since C++11) introduced something a little smarter...
Last updated
Was this helpful?