可能的重复项:
while和for循环的范围是什么?
for (int32 segNo = 0; segNo < 10; ++segNo)
{
my_Object cm;
}
对象 cm 的构造函数和析构函数是否会在每次通过循环时调用?
如果是这样,是在循环变量递增之前还是之后调用析构函数?
是的。析构函数在增量之前调用。我知道,简短的回答,但仅此而已。
#include <iostream>
struct Int {
int x;
Int(int value):x(value){}
bool operator<(int y)const{return x<y;}
void increment() { std::cout << "incremented to " << ++x << "n";}
};
struct Log {
Log() { std::cout << "Log createdn";}
~Log() { std::cout << "Log destroyedn";}
};
int main()
{
for(Int i=0; i<3; i.increment())
{
Log test;
}
}
结果:
Log created
Log destroyed
incremented to 1
Log created
Log destroyed
incremented to 2
Log created
Log destroyed
incremented to 3
对象的生命在这些大括号内。
默认构造函数在代码的第 3 行调用。当您到达 } 时,将调用析构函数。然后你的循环递增,然后检查条件。如果它返回 true,则创建另一个对象(并调用构造函数)。