在 C++ 中管理内存的理念是什么? [英] What is the philosophy of managing memory in C++?

查看:36
本文介绍了在 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++ 标准库提供了一整套容器(例如,vectormap)和像 map 这样的智能指针code>shared_ptr(来自 C++ TR1、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屋!

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