overloading new

S

shrey

Hi
I am wondering if I can overload new so that I can count how many
instances does it create of different classes. Like for example, an
example output can be Class A - 10 times, Class B - 20 etc.

Can something like that be done with minimal modifications to the
source code?


thanks
shrey
 
K

Krishna

Shery,
You can overload new operator with the following way.
ObjAny = new (user-args) type;
The above statement calls the following overloaded new operator
function.
void *operator new( type size, user args )
{
.....
}

in the overloaded function use a static variable and keep incrementing
it.


--Krishna
 
I

Ian Collins

shrey said:
Hi
I am wondering if I can overload new so that I can count how many
instances does it create of different classes. Like for example, an
example output can be Class A - 10 times, Class B - 20 etc.

Can something like that be done with minimal modifications to the
source code?
No, unless you give each class its own operator new. If you replace the
global operator, all that is passed is the number of bytes to allocate.

If you realy want to know this information, add a static counter to the
classes.
 
A

Axter

shrey said:
Hi
I am wondering if I can overload new so that I can count how many
instances does it create of different classes. Like for example, an
example output can be Class A - 10 times, Class B - 20 etc.

Can something like that be done with minimal modifications to the
source code?


thanks
shrey

For an example, check out the following link:
http://code.axter.com/leaktracker.h

The above link is a free leak tracking code that uses this method to
count calls to new and delete.

----------------------------------------------------------------------------------------
David Maisonave
http://axter.com

Author of Axter's policy based smart pointers
(http://axter.com/smartptr)
Top ten member of C++ Expert Exchange:
http://www.experts-exchange.com/Cplusplus
----------------------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top