Suppose that we have an object A, whose constructor allocates lots of resources and the destructor frees that.
class A{ public: A() { //Allocate resources, memory, handles etc. } ~A() { //Free resources, memory, handles etc. } //other functions void foo(); void bar();}
size=3>
A typical usage of A may be:
main(){ A a1; ... ... a1.foo() ... ... A a2; ... .. a2.bar() .. .. //other lengthy logic. .. //a1 and a2 will be destructed here..}
size=3>
The problem with the above approach is that a1 and a2 will not be destructed until the end of the program. Using nested scopes forces the destruction of the objects immediately after their usage:
main(){ { A a1; ... ... a1.foo() ... //a1 will be desturcted here } ... { A a2; ... .. a2.bar(); //a2 will be desturcted here } .. .. //other lengthly logic. ..}
size=3>