C ++的内存管理和.NET内存管理之间的区别是什么? [英] What is the difference between C++ memory management and .NET memory management?

查看:139
本文介绍了C ++的内存管理和.NET内存管理之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与C ++的内存管理和.NET内存管理的区别是什么?

What is the difference between C++ memory management and .NET memory management ?

推荐答案

在C ++中,您可以分配静态存储对象,使他们周围的整个程序,分配他们时,他们是当地的一个函数栈上(在这种情况下,它们破坏了包含块退出时),或分配他们在堆(在这种情况下,当你通过显式调用相应的解除分配功能这么说他们只是破坏)。堆内存分配为原料的内存与的malloc ,并发布了与免费,或分配,构建成一个对象,然后摧毁了对象,并发布了与删除。

In C++, you can either allocate objects with static storage so they are around for the whole program, allocate them on the stack when they are local to a function (in which case they are destroyed when the containing block exits), or allocate them on the heap (in which case they are only destroyed when you say so by explicitly calling the appropriate de-allocation function). Heap memory is allocated as raw memory with malloc and released with free, or allocated and constructed into an object with new, and then the object destroyed and the memory released with delete.

C#明确规定的无限怀念一种错觉---你不能释放内存,只分配内存和构造对象与。相反,GC回收内存为你再也不能访问,以便它可以重复使用的新对象的对象。

C# provides an illusion of infinite memory --- you cannot free memory explicitly, only allocate memory and construct an object with new. Instead the GC reclaims the memory for objects you can no longer access so that it can be reused for new objects.

在C ++中,类析构函数当一个对象被销毁运行。这给每个对象有机会释放所有相关的资源,他们是否多个对象,或外部资源,如文件句柄或数据库句柄。

In C++, class destructors are run when an object is destroyed. This gives each object a chance to release any associated resources whether they are more objects, or external resources such as file handles or database handles.

在C#中,你必须明确地调用释放功能管理的非内存资源的释放。该使用工具使你可以让编译器调用的Dispose()自动为您,但是这仍然是从分离对象寿命---为对象的存储器被当GC系统决定再生(其可以是从不)。

In C#, you must explicitly manage the release of non-memory resources by calling a release function. The using facility allows you to get the compiler to call Dispose() automatically for you, but this is still separate from the object lifetime --- the memory for the object is reclaimed when the GC system decides to (which may be never).

在C ++中,像的std :: shared_ptr的设施(或的boost :: shared_ptr的与旧的编译器)允许你路过引用计数的对象销毁堆对象转移到C ++运行时的责任。当的shared_ptr 的引用给定对象的最后一个实例被破坏,则引用的对象被销毁,也和它的内存回收。这样就避免了许多与手动内存管理相关的缺陷。

In C++, facilities like std::shared_ptr (or boost::shared_ptr with older compilers) allow you to pass the responsibility of destroying heap objects over to the C++ runtime by reference-counting the objects. When the last instance of shared_ptr that references a given object is destroyed, then the referenced object is destroyed too and its memory reclaimed. This avoids many of the pitfalls associated with manual memory management.

这篇关于C ++的内存管理和.NET内存管理之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆