问题
For example:
for (i=0;i<10;i++)
{
myclass = new myclass();
// do stuff with myclass
}
Questions:
- How will all the memory that has been allocated by doing 10 allocations in this case be retrieved?
- What will my memory footprint be at the end of execution?
- With delete functionality in C++, one had more control over this but in this case, for the second iteration, myclass would simply take a new allocation and move on?
回答1:
Since there are no more references to each new object after the next iteration*, they're eligible to be garbage-collected. But because you don't know when said garbage collection is going to happen, there's no straight answer as to what the memory footprint might be in the end.
Refer to MSDN: Garbage Collection for more details.
* Unless the constructor adds a reference to the object somewhere it'll stick.
来源:https://stackoverflow.com/questions/13925141/how-does-c-sharp-manage-memory-allocated-by-a-new-operator-inside-a-loop