Bonnev
Bonnev

Reputation: 987

End of scope clears variables from memory?

From this question I understand that in C# after the end of scope in most cases the garbage collector collects the variables.

But in C++ there is no garbage collector, yet I still can do this:

{
    int a = 0;
}

{
    int a = 10;
}

What happens with the variables in the memory at the end of the scope with C++?

Upvotes: 0

Views: 317

Answers (2)

user1061392
user1061392

Reputation: 324

You do not need a garbage collector for this. This is done in the stack. whenever you are done from the first one it is going to overwrite it with the second one. The only thing that you have to wary about is the variables that declared using new or malloc. When using new or malloc, the variables will be stored in the heap. if you do not delete or free the unused variables you will have memory leak.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

After exiting the scope local variables are desytoyed. If the type of a local carible is a user defined type then the destructor is called.

Upvotes: 1

Related Questions