What is the philosophy of managing memory in C++?(在 C++ 中管理内存的理念是什么?)
问题描述
在 C++ 中管理内存的设计因素是什么?例如:程序退出前没有释放内存对象,为什么会出现内存泄漏?一个好的编程语言设计不是应该维护一个处理这种情况的foo-table"吗?我知道我有点天真,但是 C++ 中关于类、结构、方法、接口、抽象类的内存管理的设计理念是什么?
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:
- 在可行的情况下,最好创建具有自动存储持续时间的对象(即,在堆栈上或函数本地)
- 每当您必须使用动态分配时,请使用范围绑定资源管理 (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 和
(来自 C++ TR1、C++0x 和 Boost)适用于大多数常见情况.map
)和像 map
这样的智能指针code>shared_ptr
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++ 中管理内存的理念是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中管理内存的理念是什么?
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01