我如何安全地(并且容易地)计数我的程序中的一个类的所有*实例? [英] How can I safely (and easily) count *all* instances of a class within my program?

查看:121
本文介绍了我如何安全地(并且容易地)计数我的程序中的一个类的所有*实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够实例化一个特定的(和其他正常的)类(我可以修改的源),并计算该类被实例化的次数(例如 like this )。但我想将所有实例包含在我的总计数中,甚至包括通过标准容器中的复制构造函数创建的实例。

I would like to be able to instantiate a particular (and otherwise normal) class (the source of which I can modify) and count the number of times the class has been instantiated (e.g. like this). But I would like to include all instances in my total count, even some which are created via the copy constructor in standard containers.

将所有构造函数(包括复制构造函数)我的类增加一个静态计数器?如果是这样,是否可以通过覆盖其他运算符来确保我的类仍然符合标准容器的要求(即,T(x)等于x)?

Would it be appropriate to have all the constructors (including the copy constructor) of my class increment a static counter? If so, is it possible to ensure my class still conforms to the requirements of standard containers (i.e., T(x) is equivalent to x), by overriding other operators for example?

推荐答案

想想静态类变量是一个全局变量,它只是在类的命名空间中。增加或执行其他操作不会对其他代码产生任何副作用,也就是说,你的构造函数和其他操作符的行为与以前一样。

Think of the static class variable as a global variable which is just in the namespace of the class. Incrementing or doing other things with it will not have any side effects on other code, i.e. your constructors and other operators will behave exactly as before.

当然,正如George指出的,如果你想拥有它的多线程安全,你需要添加一些多线程安全代码来访问你的计数器变量(例如一些mutex)。或者正如Steven指出的,你也可以使用原子增量/减量指令(但是使用将取决于平台)。这些会更快。但是,您必须小心,因为在某些情况下,它不能在多处理器环境中工作。您可以使用Boost的 atomic_count 来保证安全。

Of course, as George pointed out, if you want to have it multithreading safe, you need to add some multithreading safe code around the access to your counter variable (for example some mutex). Or as Steven pointed out, you might also use atomic increment/decrement instructions (but the usage will depend on the platform). Those would be a lot faster. Though, you have to be careful because in some cases that wont work in multi-processor environments. You can use Boost's atomic_count to be on the safe side.

这篇关于我如何安全地(并且容易地)计数我的程序中的一个类的所有*实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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