Am I required to free up memory for every variable I am no longer using?
If yes, how?
Am I required to free up memory for every variable I am no longer using?
If yes, how?
No. You do not have to free variable memory.
Then variables by value never need to release their objects because the values are stored in the variable's own area. These variables can be in stack or inside objects.
Some variables are by reference. That is, they hold a pointer to objects, typically in a dynamic area of memory called heap .
Note that even if a variable by value is inside an object that is in heap , its destruction will be automatic on object destruction. The basic rule is that it is only necessary to have a manual or automatic release when there is a pointer presence (there are several types)
Many of these objects manage their lifespan and release the memory allocated to them when their use is no longer necessary. That is, when the pointer variable ceases to exist, the object itself is in charge of destroying itself. So you do not have to worry.
When the object does not have this functionality, it is still possible to automate this with so-called smart pointers . This means you do not have to worry about the release.
These techniques are always recommended. It is most recommended to still use pointers whenever possible.
Today a modern program in C ++ hardly has to worry about manual memory release.
Of course, if you're going to build a new class, you'll probably have to build the self-management engine for it. This is one of the few moments where you need to deal with the release of memory. Even in these cases, it is often possible to replace a raw pointer with a smart pointer (mentioned above) and not worry too.
Manual:
class Exemplo {
resource* recurso;
Exemplo () : recurso(new resource) { }
~Exemplo () { delete recurso; }
};
Automatic:
class Exemplo {
std::unique_ptr<resource> recurso;
Exemplo() : recurso(new resource) { }
};
Otherwise, you can make use of manual release for learning purposes.
If you allocate memory manually you have to release symmetrically with the allocation. If you use the C technique using malloc()
, you will have to use a simple free()
. This form is considered obsolete in most situations in C ++.
If you use the new
operator of C ++, you'll have to use delete
to free memory. If it is an array , it will use new[]
and delete[]
. But again, I only advise using one of these memory controls within classes. The release will typically occur within the destructor .
Obviously in simple applications that will end soon or in some allocation that should last throughout the execution of the application there are no problems of leakage. The end of the application will free all memory allocated by it. The problem only occurs when there are more complex allocations that need to be discarded during execution so as not to jam memory.