在C++中删除堆栈变量

rra*_*azd 2 c++ variables stack scope

在C++中,如果我们在函数内部声明一个堆栈变量,它是在函数末尾自动删除还是在程序执行结束时删除?

此外,对于C语言,这个问题的答案是否相同?

Pla*_*ure 6

对于堆栈声明的变量,将调用析构函数并在内存超出范围时回收内存.

请注意,如果变量是在内部块中声明的,如if语句或循环,则这并不意味着在函数的末尾.

int main(int argc, char **argv)
{
    int a = 3;

    if (argc > 1)
    {
        int b = 5;
        ++b;
    } // b is destructed here

    // a is destructed here
    // argv and argc are destructed here (or with a)
}
Run Code Online (Sandbox Code Playgroud)

编辑:关于如何退出范围无关紧要的事实是一个很好的观点.所以...

#include <vector>
# include <exception>

int main(int argc, char **argv)
{
    std::vector<int> myVector(10);

    try
    {
        if (argc)
        {
            int a = 10;
            int b = 12;
            for (int c = 0; c < b; c++) // lol
            {
                int c_squared = c*c;
                int theEleventhElement = myVector.at(c);
                // the above will throw std::out_of_range at some point!
            }
        }
    }
    catch (std::out_of_range &ex)
    {
        // do nothing
    }
}
Run Code Online (Sandbox Code Playgroud)

当上面抛出时,堆栈将作为异常处理的一部分展开.因此,变量将按以下顺序销毁:

  • c_squared
  • c
  • ba(我认为的顺序,但如果这是在标准规定的,我不知道)

此时,最后一个catch处理程序myVector仍然只在范围内.该块忽略异常,然后main结束 - 在该点myVector被破坏.