Consider the following program:
int main() {
while(...) {
int* foobar = new int;
}
return 0;
}
When does foobar
go out of scope?
I know when using new
, attributes are allocated on the heap and need to be deleted manually with delete
, in the code above, it is causing a memory leak. However, what about scope?
I thought it would go out of scope as soon as the while loop terminates, because you have no direct access to it anymore. For example, you cannot delete
it after the loop has terminated.
Be careful here, foobar
is local to the while loop, but the allocation on the heap has no scope and will only be destructed if you call delete on it.
The variable and the allocation are not linked in any way as far as the compiler is concerned. Indeed, the allocation happens at run time, so the compiler never even sees it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With