How does C# manage memory allocated by a new operator inside a loop?

戏子无情 提交于 2019-12-23 15:44:56

问题


For example:

for (i=0;i<10;i++)
{
   myclass = new myclass();
   // do stuff with myclass
}

Questions:

  1. How will all the memory that has been allocated by doing 10 allocations in this case be retrieved?
  2. What will my memory footprint be at the end of execution?
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!