在C ++中管理内存的理念是什么? [英] What is the philosophy of managing memory in C++?
问题描述
例如:当程序退出之前不释放内存对象时,为什么会出现内存泄漏?是不是一个好的编程语言设计应该保持一个foo-table,照顾这种情况?我知道我有点幼稚,但C ++中关于类,结构,方法,接口,抽象类的内存管理的设计哲学是什么?
人们不能人为地记住每个C ++规范。内存管理的核心驱动设计是什么?
内存的核心驱动设计是什么管理?
几乎在所有情况下,都应该使用自动资源管理。基本上:
- 无论实际操作如何,更喜欢创建具有自动存储持续时间的对象(也就是在堆栈或功能 - 本地)
- 只要您必须使用动态分配,请使用范围限制资源管理(SBRM;更常称为资源获取正在初始化或RAII)。
很少有必要编写自己的RAII容器:C ++标准库提供了一整套容器(例如 vector
和 map
)和智能指针,如 shared_ptr
(从C ++ TR1, C ++ 0x和Boost)在大多数常见情况下工作得很好。
基本上,在非常好的C ++代码中,你不应该调用 delete
自己 1 来清理您分配的内存:内存管理和资源清理应该始终封装在某种容器中。
1。显然,这里的例外是您自己实施RAII容器时,因为该容器必须负责清理所有的内容。
Apologies for the vast scope of question. But what is the design factor in managing memory in C++? For example: why is there a memory leak when a program does not release a memory object before it exits? Isn't a good programming language design supposed to maintain a "foo-table" that takes care of this situation ? I know I am being a bit naive, but what is the design philosophy of memory management in C++ with respect to classes, structs, methods, interfaces, abstract classes?
Certainly one cannot humanely remember every spec of C++. What is the core driving design of memory management?
What is the core driving design of memory management ?
In almost all cases, you should use automatic resource management. Basically:
- Wherever it is practical to do so, prefer creating objects with automatic storage duration (that is, on the stack, or function-local)
- Whenever you must use dynamic allocation, use Scope-Bound Resource Management (SBRM; more commonly called Resource Acquisition is Initialization or RAII).
Rarely do you have to write your own RAII container: the C++ standard library provides a whole set of containers (e.g., vector
and map
) and smart pointers like shared_ptr
(from C++ TR1, C++0x, and Boost) work very well for most common situations.
Basically, in really good C++ code, you should never call delete
yourself1 to clean up memory that you've allocated: memory management and resource cleanup should always be encapsulated in a container of some kind.
1. Obviously, the exception here is when you implement an RAII container yourself, since that container must be responsible for cleaning up whatever it owns.
这篇关于在C ++中管理内存的理念是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!