Search code examples
c++scopeobject-lifetime

Object scope and lifetime in a for loop


Suppose I have the following code.

vector<Cat> v; \\Cat is a class
for (int i = 0; i < 5; i++)
{
    Cat cat1;
    if (someFunction(i))
    {
        cat1.setName("Whiskers");
        v.push_back(whiskers) ;
    }
}

My question is, in a for loop, does the object cat1 go out of scope while executing 0 to 4? That is will the destructor get called 5 times here or just once?


Solution

  • Constructor and destructor are called 5 times, right.

    Because control flow crosses 5 times the initialization of cat, and 5 times the end of its scope (the closing '}' of loop block).

    Actually, what you see in the outermost brace is actually one composite statement repeated while the loop condition (i < 5) is true.