【问题标题】:What is the lifetime and scope of the enclosed loop variable? [duplicate]封闭循环变量的生命周期和范围是多少? [复制]
【发布时间】:2012-12-07 21:35:26
【问题描述】:

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

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

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

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

【问题讨论】:

  • @bames53 您的链接无法回答变量是在增量之前还是之后销毁。

标签: c++ loops scope


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    #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
    

    【讨论】:

      【解决方案3】:

      对象的生命在那些花括号里面。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-23
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        相关资源
        最近更新 更多