最简单的方法来计算对象的实例 [英] Simplest way to count instances of an object

查看:156
本文介绍了最简单的方法来计算对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在某个执行点分配的某些对象的实例的确切数量。主要用于狩猎可能的内存泄漏(我大多使用RAII,几乎没有新的,但仍然可以忘记向量上的.clear()添加新元素或类似的东西)。 Ofc我可以有一个

I would like to know the exact number of instances of certain objects allocated at certain point of execution. Mostly for hunting possible memory leaks(I mostly use RAII, almost no new, but still I could forget .clear() on vector before adding new elements or something similar). Ofc I could have an

atomic<int> cntMyObject;

我在析构函数中,++增加构造函数,cpy构造函数:))。
这是每个类的硬编码。它不是简单的在释放模式禁用它。
那么有没有简单的优雅方法可以很容易地禁用计数对象实例?

that I -- in destructor, ++ increase in constructor, cpy constructor(I hope I covered everything :)). But that is hardcoding for every class. And it is not simple do disable it in "Release" mode. So is there any simple elegant way that can be easily disabled to count object instances?

推荐答案

对象类,在其构造函数和析构函数中进行适当的引用计数,然后派生您要从中跟踪的对象。

Have a "counted object" class that does the proper reference counting in its constructor(s) and destructor, then derive your objects that you want to track from it. You can then use the curiously recurring template pattern to get distinct counts for any object types you wish to track.

// warning: pseudo code

template <class Obj>
class CountedObj
{
public:
   CountedObj() {++total_;}
   CountedObj(const CountedObj& obj) {if(this != &obj) ++total_;}
   ~CountedObj() {--total_;}

   static size_t OustandingObjects() {return total_;}

private:
   static size_t total_;
};

class MyClass : private CountedObj<MyClass>
{};

这篇关于最简单的方法来计算对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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