By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,806 Members | 1,457 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,806 IT Pros & Developers. It's quick & easy.

overloading new

P: n/a
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

Apr 21 '06 #1
Share this Question
Share on Google+
5 Replies


P: n/a
you can use static member variable for this requirement.

Apr 21 '06 #2

P: n/a
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

Apr 21 '06 #3

P: n/a
shrey wrote:
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.

--
Ian Collins.
Apr 21 '06 #4

P: n/a
le******@gmail.com wrote:
you can use static member variable for this requirement.

What requirement? Please quote context.

--
Ian Collins.
Apr 21 '06 #5

P: n/a
shrey wrote:
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
----------------------------------------------------------------------------------------

Apr 21 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.