First of all, I think you should consider using a memory leak detector in your programms, so you can know by yourself if your code is leaking and if you have to do something about it. In your code you would have seen that there is no need to delete anything. :)
As far as I know, you should worry about memory in only two cases:
- You have allocated a C-style array with
malloc
or calloc
. In this case, you need to use the function free
to deallocate the array. But generally in C++, you don't want this. You prefer using a container like std::array
or std::vector
instead.
- You have created a new instance of an class with
new
and you have got a pointer to this instance. In this case, you have to use delete
on the pointer when you don't need this instance anymore. But generally in C++11 (or further), you don't want this. If you really have to use a pointer, you prefer creating a smart pointer like std::unique_ptr
or std::shared_ptr
which will handle the memory for you.
When you define a variable without using new
, malloc
or calloc
, (for example int a = 1 ;
), it will be automatically deleted when it goes out of scope. So you don't need to worry.
Here is a simple example of a variable going out of scope:
int a = 1 ;
{
int b = 1 ;
// b is implictly deleted here, just before the bracket.
}
a++; // It works, because a exists in this scope
b++; // It doesn't work, because b is out of scope.
// a is implicitly deleted here, assuming we are at the end of a function