C ++-如果在循环中声明对象,则在循环结束时调用其析构函数吗? [英] C++ - If an object is declared in a loop, is its destructor called at the end of the loop?

查看:253
本文介绍了C ++-如果在循环中声明对象,则在循环结束时调用其析构函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,对象的析构函数在创建它的块的结尾处的}"处被调用,对吗?因此,这意味着如果我有:

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)
{
    SomeClass some_object;
    some_object.someFunction();
    some_variable = some_object.some_member;
}

然后在循环的一次迭代中创建的对象的析构函数将在循环的结尾被调用,然后再创建另一个对象,对吗?

Then the destructor for the object created in one iteration of the loop will be called at the end of the loop before another object is created, correct?

谢谢.

推荐答案

是.

但是您可以自己测试一下.这是一种语言功能,编译器不太可能会出错.

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

#include <iostream>

struct S {
  S() { std::cout << "S::S()\n"; }
  ~S() { std::cout << "S::~S()\n"; }
};

int main () {
  int i = 10;
  while(i--) {
    S s;
  }
}

这篇关于C ++-如果在循环中声明对象,则在循环结束时调用其析构函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆