查找 c++ 中单个类的内存使用情况
我有一个类 classX
并且想知道该类的所有实例使用了多少内存。每个新实例都是使用 new classX 创建的
有没有办法在不修改源代码的情况下执行此操作(即使用 valgrind 等工具)?
而我可以用什么方法通过修改源代码来做到这一点(我不能修改每个实例创建,但可以修改类本身)。
我能想到的唯一方法是重载 new 运算符(但我不知道如何从那里调用原始的 new 运算符)!
I have a class classX
and would like to know how much how much memory all of the instances of this class use. Every new instance is created using new classX
Is there a way to do this without modifying source code (ie using tools like valgrind)?
And what methods can I use to do this by modifying the source code (I can't modify each instance creation, but can modify the class itself).
The only method I can think of is to overload the new operator (but I don't know how to call the original new operator from there)!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
如果您想跟踪堆栈上对象使用的空间,最好在构造函数和析构函数中添加跟踪。像这样的东西应该可以完成工作。
唯一潜在的问题是,您可能还需要跟踪动态分配的成员。
class Tracked
{
static int space_used;
static int space_released;
Tracked() { space_used += sizeof(Tracked); }
~Tracked() { space_released += sizeof(Tracked); }
};
int Tracked::space_used = 0;
int Tracked::space_released = 0;
int main()
{
{
Tracked t;
Tracked * t_ptr = new Tracked();
}
std::cout<<"used :"<< Tracked::space_used <<std::endl;
std::cout<<"released :"<< Tracked::space_released <<std::endl;
std::cout<<"live :"<< Tracked::space_used - Tracked::space_released <<std::endl;
}
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在类中重载
operator new()
非常容易。然后可以使用::
调用全局命名空间来指定全局命名空间,如::operator new()
中所示。像这样的东西:It's quite easy to overload
operator new()
in the class. The global one can be then called using::
to specify global namespace as in::operator new()
. Something like this: