C++ - 如果在循环中声明对象,是否在循环结束时调用其析构函数
C++ - If an object is declared in a loop, is its destructor called at the end of the loop?
在C++中,对象的析构函数在创建它的块的结束"}"处调用,对吗?所以这意味着如果我有:
while(some_condition)
{
SomeClass some_object;
some_object.someFunction();
some_variable = some_object.some_member;
}
那么在循环的一次迭代中创建的对象的析构函数将在循环结束时调用,然后再创建另一个对象,对吗?
谢谢。
是的。
但是你可以自己测试一下。这是编译器不太可能出错的语言功能。
#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;
}
}
可观察到的行为是它被称为每次迭代。
不过,有关优化的常规规则仍然适用。如果编译器很聪明并且对象简单,那么编译器可以做任何它喜欢的事情,仍然产生正确的行为,例如:
#include <iostream>
struct foo {
int i;
foo() : i (-1) {}
~foo() { i = 1; }
};
int main() {
int i = 10;
while (--i) {
foo f;
std::cout << f.i;
}
}
编译为:
.Ltmp5:
.cfi_def_cfa_register %rbp
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
movl $_ZSt4cout, %edi
movl $-1, %esi
callq _ZNSolsEi
xorl %eax, %eax
popq %rbp
ret
即展开并且那里没有该析构函数的迹象(尽管可观察到的行为仍然相同(。
相关文章:
- 为什么在这个代码结束循环中没有得到结束
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 使用 shared_ptr 在中断时结束多线程循环
- 如何使用循环结束 c++ 上的行
- 具有迭代器和自定义步长的循环结束条件
- 为什么这个 while 循环在下面的代码中没有结束?
- 为什么在使用不相关的宏时会阻止 while 循环结束?
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- while 循环 C++ 结束,但不继续到其余语句
- 为什么循环结束时不这样做?
- 向量中指针的前半部分在循环结束后被重新分配
- For 循环结束自身并终止正在运行的程序,但在删除斜率计算语句时正常运行
- 有没有一个C++版本在循环结束后将在for循环初始化中声明的变量保留在作用域中
- 数组循环在循环结束后输出垃圾
- C++ - 如果在循环中声明对象,是否在循环结束时调用其析构函数
- Dlsym以无限循环结束
- 为什么我总是以无限循环结束
- 崩溃控制台应用程序,在循环结束时.寻求建议.(图片在里面)
- 在while循环结束时清除c++字符串
- Vector迭代器+偏移量超出范围,在while循环结束时给出错误