I think I understand how the stack works and what happens when a variable gets moved, but I can't find an answer to this question. Let me explain:
When a new scope is entered/created, a certain amount of memory is acquired on top of the stack. The stack pointer points to this memory. It represents the current size of the stack. When the scope is left, the memory is freed by having the stack pointer return to it's previous position.
Move semantics in C++11 or later move ownership of some data from one variable to another. This avoids copying data, because the memory holding the data stays the same. After the move, the moved-to variable points to the data's location in memory, and the moved-from variable basically becomes a null pointer. Here I might be making my first mistake, by relating move semantics to pointers too closely. Am I?
The actual question: A variable is created in an inner scope and then moved to a variable in an outer scope. Then the inner scope exits. What happens to the stack?
Given the above, the stack pointer should return to it's previous position and free the inner scope memory. But it cannot do this, since the memory from the inner scope is still valid, since it's now attached to the outer scope variable. There might be a lot of memory blocked/wasted in between the outer (possibly global) scope and the formerly inner scope memory. This memory becomes available again once the outer scope exits. Until then, stack size is inflated. Is this true? Can this be avoided? Does the compiler prevent this?
Aucun commentaire:
Enregistrer un commentaire