如何C#管理分配由新的运营商在循环中的记忆?运营商、分配、记忆

2023-09-04 13:32:48 作者:抹去浮华虚夸

例如:

 为(i = 0;我小于10;我++)
{
   MyClass的=新MyClass的();
   //做的东西有MyClass的
}
 

问题:

如何将所有已分配通过执行10分配在这种情况下,存储器检索? 将我的内存占用是在执行的到底是什么? 在C ++中删除功能,人有更多的控制权这一点,但在这种情况下,第二次迭代,MyClass的只会把一个新的分配,并继续前进? 解决方案

由于有下一次迭代*后,每个新对象的更多引用,他们有资格进行垃圾回收。但是因为你不知道的在的说,垃圾收集的事情发生,没有直接答复,内存占用可能是到底是什么。

参阅 MSDN:垃圾回收了解更多详细信息

*除非构造增加了一个参考对象的地方,它会坚持下去。

python基础 03三大流程控制 顺序,分支,循环

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?

解决方案

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.