c++ - 循环内局部对象的析构函数是否保证在下一次迭代之前被调用?

标签 c++ destructor

当我有一个循环并在该循环内创建一个新的堆栈变量(未将其分配在堆上并将其保存在循环体内声明的变量上)时,是否保证在下一次迭代开始之前调用该对象的析构函数,或者编译器的循环展开可能会改变一些事情?

最佳答案

来自n4800:

§6.3.3 block 范围:

A name declared in a block (8.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (6.3.2) and ends at the end of its block. A variable declared at block scope is a local variable.

§10.3.6 析构函数:

A destructor is invoked implicitly [...] when the block in which an object is created exits (8.7)

§4.1.1 抽象机:

This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this document as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.

[强调我的]

所以,是的。您的变量在循环结束时超出范围(这是一个 block ),因此它的析构函数被称为据任何观察程序行为的人所知

关于c++ - 循环内局部对象的析构函数是否保证在下一次迭代之前被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212964/

相关文章:

c++ - 隐式类型转换的临时工的生命周期

c++ - 在大数乘法上使用 FFT 的问题

c++ - 从析构函数调用非成员函数可以吗?

不调用 C++ 析构函数

c++:for循环增量部分中的操作顺序

c++ - 用宏隐藏 void* 指针的机制

c++ - 获取 DLL 中定义的函数列表

c++ - 在分配为不同类型的数组上使用 delete[] 是否安全?

c++ - 保证在处置类(class)时处置类(class)成员

c++ - 多线程段故障析构函数