标准库使用的重写内存分配方法? [英] Overriding memory allocation method standard libraries use?

查看:64
本文介绍了标准库使用的重写内存分配方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以重写STL分配,管理和释放内存的方式?如果可能的话,将如何做?有没有一种方法可以将处理原始内存的代码保存在一个类或文件中?

我想在整个程序中执行此操作,以便可以跟踪内存使用情况,时间安排和生命周期信息.当然纯粹出于好奇!

解决方案

您可以通过在其中一个文件中重新定义运算符newdelete来做到这一点.

解析符号时,链接程序将覆盖您的标准链接符.

您会在SO上找到很多答案,就像这样:重载new/delete 或那个:如何在C ++中跟踪内存分配(尤其是新的/删除的).

互联网上也有一些图书馆为您提供帮助,例如 Memtrack . SO对此也有一些资源: C ++内存泄漏自动检测库. /p>

Is it possible to override the way STL allocates, manages, and frees memory? How would one do so, if it's possible? Is there a way to do this in a way that keeps the code that handles the raw memory in one class or file?

I would like to do this for my entire program so I can keep track of memory usage, timing, and lifetime info. Purely out of curiousity of course!

解决方案

You can do that by redefining the operators new and delete in one of your files.

The linker will override the standard ones by yours when resolving symbols.

You'll find lots and lots of answers on SO, like this one: overloading new/delete or that one: How to track memory allocations in C++ (especially new/delete) .

There exist some libraries on the internet that do that for you as well, like Memtrack or this one . SO has also some resources on that: C++ memory leak auto detection library .

这篇关于标准库使用的重写内存分配方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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