Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any guarantee for the order in which C++ stack variables are destroyed

Tags:

c++

Consider the following code:

{
  std::auto_ptr<Something> p1(pSomePointer);
  std::auto_ptr<Something> p2(pSomeOtherPointer);
  ...
}

Is there any guarantee that p2 destructor will be called before p1's when exiting the scope? Common sense says that the stack variables should be destroyed from top of the stack first but C++ compiler can reorder assignments.

like image 668
S. Georgiev Avatar asked Nov 12 '10 14:11

S. Georgiev


1 Answers

Yes, they are destroyed in order opposite to the construction order - objects constructed last will be destroyed first. C++ guarantees this.

like image 183
sharptooth Avatar answered Oct 14 '22 07:10

sharptooth