封闭循环变量的生命周期和范围是多少?

时间:2012-12-07 21:35:27

标签: c++ loops scope

  

可能重复:
  What is the scope of a while and for loop?

for (int32 segNo = 0; segNo < 10; ++segNo)
{
    my_Object cm;
}

每次通过循环时都会调用对象cm的构造函数和析构函数吗?

如果是这样,是否会在循环变量递增之前或之后调用析构函数?

3 个答案:

答案 0 :(得分:8)

是。并且在增量之前调用析构函数。我知道,简短的回答,但就是这样。

答案 1 :(得分:6)

#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 created\n";}
  ~Log() { std::cout << "Log destroyed\n";}
};

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

答案 2 :(得分:5)

物体的寿命在那些花括号内。

在代码的第3行调用默认构造函数。当你到达}时,将调用析构函数。然后递增循环,然后检查条件。如果它返回true,则创建另一个对象(并调用构造函数)。