# How do you destroy variables that are still in scope

## Recommended Posts

My ap has diffrent states. Each state uses diffrent variables. Instead loading them all at the start of the program, I was wondering how to destroy them the ones that are needed any more as I move from one state to another. My question would span variables and class objects (i.e. SomeClass someclass). Any suggestions? Regards Chad

##### Share on other sites
jpetrie    13103
You don't, unless you allocated them yourself via new. If you did, you can kill them off whenever you feel like it by deleting them. However, everything else is controlled by its scope, and you don't want to mess with that or you'll cause undefined behavior.

Care to provide a more in-depth example? If each state is modelled as a different class, you only need to create and destroy an instance of the class to effectively control the lifetime of the variables in that class. There is no need to allocate them all at startup, necessarily.

##### Share on other sites
SimonForsman    7642
create blocks for the variables in question to dictate their scope at compile time.

example.
function a() {    int x=6;    {        int x=3;        std::cout << x << std::endl;    }    std::cout << x << std::endl;}