在C ++中管理内存的哲学是什么? [英] What is the philosophy of managing memory in C++?
问题描述
对于广泛的问题深表歉意。但是在C ++中管理内存的设计因素是什么?
例如:为什么程序在退出前没有释放内存对象时会出现内存泄漏?是不是一个好的编程语言设计应该维护一个foo表,照顾这种情况?我知道我有点天真,但是C ++中的内存管理在类,结构,方法,接口,抽象类方面的设计哲学是什么?
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?
当然人们不能人道地记住每一个C ++的规范。
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:
- 无论在什么情况下这样做,首选创建具有自动存储持续时间的对象(即在堆栈或函数 - local)
- 每当您必须使用动态分配时,请使用范围绑定资源管理(SBRM;更通常地称为资源获取正在初始化或RAII)。
- 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).
很少需要编写自己的RAII容器:C ++标准库提供了一整套容器(例如 vector
和 map
)和智能指针如 shared_ptr
C ++ 0x和Boost)对于大多数常见情况非常有效。
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.
基本上,在非常好的C ++代码中,不应调用 delete
自己 1 清理已分配的内存:内存管理和资源清理应该总是封装在某种容器中。
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。显然,这里的例外是当你自己实现一个RAII容器,因为该容器必须负责清理它拥有的任何东西。
这篇关于在C ++中管理内存的哲学是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!