C++ - If an object is declared in a loop, is its destructor called at the end of the loop?
c++, class, loops, object
Solution
Yes.
But you could have tested it yourself. This is a language feature that compilers are unlikely to get wrong.
#include <iostream>
struct S {
S() { std::cout << "S::S()\n"; }
~S() { std::cout << "S::~S()\n"; }
};
int main () {
int i = 10;
while(i--) {
S s;
}
}
Problem
In C++, an object's destructor is called at the closing "}" for the block it was created in, right? So this means that if I have: ``` while(some_condition) { SomeClass some_object; some_object.someFunction(); some_variable = some_object.some_member; } ``` Then the destructor for the object created in one iteration of the loop will be called at the end of the loop before another object is created, correct? Thanks.