1

Normally, when you exit, let's say for loop, variables declared inside are deleted. For example:

for(int i=0; i<10; i++)
{
    vector <int> v;
    for(int j=0; j<1000000; j++) v.push_back(j);
}

Despite creating vector with size of 1000000, memory is free after loop.

If we do sth like this:

for(int i=0; i<10; i++)
{
    vector <int> v;
    for(int j=0; j<1000000; j++) v.push_back(j);
    goto after_for;
}
after_for: ;

will the vector stay in memory or be deleted?

miszcz2137
  • 894
  • 6
  • 18
  • 3
    Is your question specific to `goto`, or is it about any way of exiting the block other than by reaching the closing `}`? For instance, for a `return` statement in the middle of a loop, or throwing an exception, are you already clear on what happens then? –  Nov 23 '17 at 14:32
  • If you look more closely at the first `for` loop, that vector is "deleted" multiple times since it is local in the outer `for` loop. On each iteration of `for (i...`, the `v` vector is destroyed and constructed. – PaulMcKenzie Nov 23 '17 at 14:34

2 Answers2

1

It gets deleted because it is no longer in scope

mkrufky
  • 3,268
  • 2
  • 17
  • 37
1

Will be deleted. The variable goes out of scope and hence destructor is called (and memory freed) This is guaranteed even if you exit this way:

for(int i=0; i<10; i++)
{
    vector <int> v;
    for(int j=0; j<1000000; j++) v.push_back(j);
    throw std::runtime_error("xyz") ;
}
marom
  • 5,064
  • 10
  • 14