473,772 Members | 3,603 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

instance counting

Good morning, C++ers,

A couple days ago i came across a useful trick for counting instances of a
given class, and i thought i'd pass it on:

Conventionally, as described in several books, to do instance counting we
subclass some base type and add a counter to that base class. IMO that is
completely unnecessary:

/**
Utility function to help keep an instance count of T.
*/
template <typename T>
unsigned long & inst_count() { static unsigned long c = 0; return c; }

Then simply do this in the ctors:
++inst_count<My Type>();

and in the dtor:
--inst_count<MyTy pe>();

This offers a feature the conventional approach does not: it allows us to
track instance counts separately for, e.g. A and B, when B subclasses A.
That it, if we use some "pure A" objects and some B objects we can
independently track A and B counts by using inst_count<> in both A and B.

Of course, this approach does suffer from the potential problem of client
code doing:

inst_count<MyTy pe>() = 10;

but i think that's far-fetched enough that it can be essentially ruled out.

--
----- stephan beal
http://s11.net/
Registered Linux User #71917 http://counter.li.org
I speak for myself, not my employer. Contents may
be hot. Slippery when wet. Reading disclaimers makes
you go blind. Writing them is worse. You have been Warned.

Jul 19 '05 #1
1 2640
"stephan beal" <st*****@s11n.n et> wrote...
Good morning, C++ers,

A couple days ago i came across a useful trick for counting instances of a
given class, and i thought i'd pass it on:

Conventionally, as described in several books, to do instance counting we
subclass some base type and add a counter to that base class. IMO that is
completely unnecessary:

/**
Utility function to help keep an instance count of T.
*/
template <typename T>
unsigned long & inst_count() { static unsigned long c = 0; return c; }

Then simply do this in the ctors:
++inst_count<My Type>();

and in the dtor:
--inst_count<MyTy pe>();

This offers a feature the conventional approach does not: it allows us to
track instance counts separately for, e.g. A and B, when B subclasses A.
That it, if we use some "pure A" objects and some B objects we can
independently track A and B counts by using inst_count<> in both A and B.

Of course, this approach does suffer from the potential problem of client
code doing:

inst_count<MyTy pe>() = 10;

but i think that's far-fetched enough that it can be essentially ruled

out.

Yes, this expression is far-fetched enough. However, this isn't:

void print(unsigned long& a) { // erroneously put '&' here
cout << a;
a = 0; // hidden reset of a variable -- unintended "reuse"
// of the parameter as a local variable
}

...
print(inst_coun t<MyType>()); // oops

But if the user remembers to put ++inst_count<>( ) in the c-tors,
then he will probably remember not to make a mistake like that...

Victor
Jul 19 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2185
by: Elbert Lev | last post by:
Please correct me if I'm wrong. Python (as I understand) uses reference counting to determine when to delete the object. As soon as the object goes out of the scope it is deleted. Python does not use garbage collection (as Java does). So if the script runs a loop: for i in range(100): f = Obj(i)
7
2421
by: max(01)* | last post by:
hi. is there a way to define a class method which prints the instance name? e.g.: >>> class class_1: .... def myName(self): .... ????what should i do here???? ....
1
3253
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that I don't understand completely. It says "A garbarage collector, such as the one used in Java, maintains a record of whether or not an object is currentlys being used. An unused object is tagged as garbage,
18
2945
by: ChadDiesel | last post by:
I appreciate the help on this group. I know I've posted a lot here the last couple of weeks, but I was thrown into a database project at my work with very little Access experience. No other employee knows anything about Access. I've searched Google Groups, and that has been a lot of help, but there are some questions that I just can't find the answer to. I'll try to take it easy on the group after this question. I have one more...
1
6929
by: j | last post by:
Hi, I've been trying to do line/character counts on documents that are being uploaded. As well as the "counting" I also have to remove certain sections from the file. So, firstly I was working with uploaded MS WORD .doc files. Using code like that below: strLine = sr.ReadLine While Not IsNothing(strLine) 'Not eof If Trim(strLine) <> "" Then 'Not blank
11
23273
by: Jon | last post by:
I want to count the number of instances of a certain string(delimiter) in another string. I didn't see a function to do this in the framework (if there is, please point me to it). If not, could someone let me know if the method I've used below is efficient or if there is a better way to do it, as these will be rather large strings I'm searching in. Thanks Public Shared Function CountDelimiter(ByVal strInput As String, ByVal...
6
2823
by: Jason Bell | last post by:
How can I find out how many references to an instance exist at any given time? I want to make it so that when the number of references is one, a countdown starts (that one reference being the one held by the resource manager). This way I can ensure that objects are only deleted if they haven't been used in an amount of time defined by the user.
4
4197
by: aaronfude | last post by:
Hi, Please consider the following class (it's not really my class, but it's a good example for my question): class Vector { int myN; double *myX; Vector(int n) : myN(n), myX(new double) { } double &operator()(int i) { return myX; }
275
12400
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10104
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.