In C++, if we declare a stack variable inside of a function, is it automatically deleted at the end of the function or is it deleted at the end of the program execution?
Also, is the answer to this question the same for the C language?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For stack-declared variables, the destructor is called and the memory reclaimed as it falls out of scope.
Note that this doesn’t mean at the end of the function if the variable is declared in an inner block, like an if-statement or loop.
EDIT: A good point was made about the fact that it doesn’t matter how the scope is exited. So…
When the above throws, the stack will unwind as part of the exception handling. Thus, the variables will be destroyed in the following order:
c_squaredcbanda(I think in that order, but I don’t know if that’s mandated in the standard)At this point, there is finally a catch handler with only
myVectorstill in scope. That block ignores the exception, and thenmainends– at THAT pointmyVectoris destructed.