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

5 c++ scope loops

可能重复:
while和for循环的范围是什么?

for (int32 segNo = 0; segNo < 10; ++segNo)
{
    my_Object cm;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Nik*_* C. 8

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


Yak*_*ont 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

Log created
Log destroyed
incremented to 1
Log created
Log destroyed
incremented to 2
Log created
Log destroyed
incremented to 3
Run Code Online (Sandbox Code Playgroud)


Bou*_*les 5

对象的生命在那些花括号内.

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