C++ - If an object is declared in a loop, is its destructor called at the end of the loop?

前端 未结 2 710
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 08:59

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)
{
             


        
2条回答
  •  不知归路
    2021-02-07 09:11

    Yes.

    But you could have tested it yourself. This is a language feature that compilers are unlikely to get wrong.

    #include 
    
    struct S {
      S() { std::cout << "S::S()\n"; }
      ~S() { std::cout << "S::~S()\n"; }
    };
    
    int main () {
      int i = 10;
      while(i--) {
        S s;
      }
    }
    

提交回复
热议问题