C ++中对象的静态和动态内存分配 [英] static and dynamic memory allocation of objects in C++
问题描述
在C ++程序中,对于一个类,我们如何获得静态创建并动态创建的任何时间点的活动对象的数量?
In a C++ program, for a class, how can we get the counts of the number of active objects at any point of time which are statically created and dynamically created separately??
推荐答案
很遗憾,你不能。
更多关于这个问题的更多信息有效的C ++ - 项目#27:要求或禁止基于堆的对象。
More Effective C++ - Item #27: Requiring or prohibiting heap-based objects.
确定这里有一个很容易演示的问题我不会总结所有的,但这里至少有一个挑战):
Ok here's one of the problems that is easily demonstrated (the item in question is several pages long so I won't summarize all of it but here's at least one challenge):
许多(但不是所有)系统以下列方式安排他们的内存:
Many (but not all) systems arrange their memory in the following fashion:
----------------
| Stack |
| (Grows Down) |
| |
----------------
| |
| |
| |
| |
| |
| |
----------------
| Heap |
| (Grows Up) |
| |
----------------
现在你可能会认为这样的内存安排,你可以做一些聪明的运算符new / new运算符,以确定你是否在堆上或不正确(通过检查,如果你在一个特定的内存位置以上或以下)。这里的问题。静态对象是系统依赖的,所以可能发生以下事情:
Now you might think with a memory arrangement like this you could do something clever with operator new/new operator to figure out if you're on the heap or not right (by checking if you're above or below a certain memory location)? Here's the problem. Where static objects go is system dependent, so the following thing could happen:
----------------
| Stack |
| (Grows Down) |
| |
----------------
| |
| |
| |
| |
| |
| |
----------------
| Heap |
| (Grows Up) |
| |
----------------
| Static |
| Objects |
----------------
您现在无法区分静态对象和堆对象。糟糕!也许你可能已经注意到我说这是系统依赖,这意味着即使你找出一种方法来区分它们,你的代码不会是可移植的。
You now fail to distinguish between static objects and heap object. Oops! Also you may have noticed I said this is system dependent, which means even if you were to figure out a way to distinguish between them, well your code would not be portable.
这篇关于C ++中对象的静态和动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!