0

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?

Andrew
  • 5,212
  • 1
  • 22
  • 40
Kevin Zakka
  • 445
  • 7
  • 19

1 Answers1

2

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.

AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27