Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does an object on the heap go out of scope

Tags:

c++

scope

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.

like image 393
whirlwin Avatar asked Dec 16 '11 17:12

whirlwin


1 Answers

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.

like image 182
dmckee --- ex-moderator kitten Avatar answered Nov 15 '22 06:11

dmckee --- ex-moderator kitten