tags:

views:

105

answers:

3

Is there any way I can find how many objects are instanciated from stack and how many objects from Heap. I dont wish to have the restrictions of scoping in objects from Stack.

If i use a static counter in constructor and destructor, it will be called in both the cases(object from stack and heap). One way is to exploit the idea are objects from stack are scoped and destructor is called when they go out of scope but i want a better solution so as to know the number of objects at any point of time.

+10  A: 

Override operator new and operator delete for the class. Have another counter there that is incremented/decremented in these operators. This will keep track of objects created on the heap. The constructor/destructor can increment/decrement another counter that will count all objects. The difference between the two is the set of objects on the stack (as well as global objects).

Tarydon
Thanks Taydon...
Sandeep
+1 brilliant - never thought of it this way.
this. __curious_geek
Oh wow, that blows my answer out of the water. Never would have thought of something like this
chustar
A: 

Tarydon's explanation works for everything except intrinsic types. For intrinsic types you can override global new and delete, but there is no real way that I know of to track intrinsic stack allocations.

Chris
Since Sandeep was talking about using a static counter in the constructor and destructor, I assumed he was not looking at intrinsic types.
Tarydon
A: 

The only solution I can think of would be to keep a count every time you instantiate or (explicitly or not) delete an object.
If an object were created with the new operator, you record it as being from the heap, otherwise, you record it as a regular variable.

chustar