How to find the memory used by any object(如何找到任何对象使用的内存)
问题描述
class Help
{
public:
Help();
~Help();
typedef std::set<string> Terms;
typedef std::map<string, std::pair<int,Terms> > TermMap;
typedef std::multimap<int, string, greater<int> > TermsMap;
private:
TermMap terms;
TermsMap termsMap;
};
我们如何找到term
和termsMap
对象使用的内存(以字节为单位).我们有图书馆吗?
How can we find the memory used (in bytes) by the objects term
and termsMap
. Do we have any library ?
推荐答案
如果您正在寻找对象的完整内存使用情况,这在 C++ 中通常无法解决 - 而我们可以获得实例的大小通过 sizeof()
自身,对象总是可以根据需要动态分配内存.
If you are looking for the full memory usage of an object, this can't be solved in general in C++ - while we can get the size of an instance itself via sizeof()
, the object can always allocate memory dynamically as needed.
如果你能找出一个容器中单个元素有多大,你就可以得到一个下限:
If you can find out how big the individual element in a container are, you can get a lower bound:
size = sizeof(map<type>) + sum_of_element_sizes;
请记住,容器仍然可以分配额外的内存作为实现细节,对于像 vector
和 string
这样的容器,您必须检查 分配大小.
Keep in mind though that the containers can still allocate additional memory as an implementation detail and that for containers like vector
and string
you have to check for the allocated size.
这篇关于如何找到任何对象使用的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何找到任何对象使用的内存
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07