Reputation: 493
Say Pokemon
is a class. Consider this snippet:
Pokemon Eve(4,3); //call to constructor, creating first object on the stack
Eve=Pokemon(3,5); //call to constructor again, creating a second object on the stack
Both objects are created on the stack. After the second line executes, the first object (with parameters 4,3) can no longer be accessed. What happens to it? What is the jargon used to describe this process? Garbage collection?
Upvotes: 1
Views: 87
Reputation: 361
The objects are not created on the heap, but directly on the stack, so no space is lost (i.e., there's no allocated space that becomes unreachable) -- the assignment simply reuses the memory allocated by the initialization of Eve
.
Edited: More careful wording around the "overwriting" contention.
Upvotes: 1
Reputation: 10316
I think you misunderstand what is happening. The object originally created as Eve
isn't 'lost' after the second line. In fact, it is still the same object afterwards (by which I mean it still has the same memory address). The second line assigns a different value to the object by calling the assignment operator on the object Eve
. The parameter passed to the assignment operator is the temporary object created by Pokemon(3,5)
.
It is the said temporary object - Pokemon(3,5)
which is destroyed after the second line. Its destruction is not 'garbage collection' or even a heap deallocation, as it is a stack object in the first place and thus doesn't require such.
I think you're thinking about this in terms of Java/C# or similar managed languages, that only have object references and not direct objects. In C++ with the code above you're dealing with objects directly. To see something equivalent to what you have in mind, consider this:
Pokemon* Eve = new Pokemon(4,3);
Eve=new Pokemon(3,5);
Here we're using pointers and the heap, rather than the stack. In this case, the second line really does 'lose' the original object, because it is the pointer that is reassigned. This is sort of similar to what happens in Java/C# with just normal assignment. The difference is, of course, that C++ doesn't have any garbage collector so in the above the original object is truly lost in the sense of being a memory leak.
Upvotes: 6
Reputation: 118330
It's called "the assignment operator", or "=".
The second object is the temporary object, not the first one. After it is constructed, the first object's assignment operator is invoked, to assign the value of the second object to the first object.
After that the second object's destructor is invoked, and the second object gets destroyed. Where it goes? To the great bit bucket in the sky. It's gone.
Upvotes: 3