If I declare an object inside a for field, is the memory freed after that?
Yes, not just inside - inside any block.
For example:
void bar()
{
foo* p;
{
foo f;
p = &f;
}
// p no longer points to a valid object, f has ended its lifetime
Same with for
, except that the object will be created / destroyed every time the loop starts.
Now, if instead you have:
void bar()
{
foo* p;
{
foo* f = new foo;
p = f;
}
// p is still valid here, you need to clean up yourself with delete
And if you do this inside a for, you need to be very careful not to leak all of these distributions.
source to share
Yes.
A for-statement has the following grammar:
for (init cond; expr) statement
And it's equivalent:
{
init
while (cond)
{
statement
expr;
}
}
Thus, anything that has been defined inside the for loop ends its lifetime at the end of the loop, both for the inner expression and for the complete control structure. Pointing out that he is no longer alive, UB.
Generally:
void* p;
{
T x;
p = &x;
} // x no longer exists
// p no longer holds a valid value
source to share
The variable will be on the stack and out of scope when the for-loop ends. If you allocate memory on the heap and assign it to a pointer declared in the for-loop, then the memory will have a dangling reference when the for loop completes, because the local reference no longer exists.
source to share
Any object declared inside a block {
and }
is destroyed after exiting that block, regardless of whether the block is used as part of a compound statement (for example, the body of a loop for
). All pointers to such objects are also invalidated.
EDIT as correctly stated by 0A0D, the lifetime of objects created with is new
explicitly controlled; they will survive block exits, but they also need to be removed manually.
source to share