gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:05:01 24 4
gpt4 key购买 nike

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

最佳答案

来自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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com