views:

161

answers:

2

In my code, i have overloaded the new and delete operators to get filename and line number. In my code I am using map and stack. When i do erase a particular value from the map it just call my overloaded delete function but I want only explicit delete statements to be able to access my function, not others. How can I do that?

+1  A: 
John Kugelman
@John - why won't `__FILE__` and `__LINE__` work?
Dominic Rodger
Because it will always be called from the file where you overload the delete operator. See my response for a way to overcome that.
Eric Fortin
yes i know but i have another way to get filename and line number. Problem is not getting the filename but its about how to stop calling delete function. My mean with explicit was not any specific type. for ex: char * ptr = new char[40]; delete ptr --- should call my delete function but suppose i have one map. if i write map.erase() it shouldnot call my delete function.
max_dev
For the specific case of map you could create your own allocator that explicitly doesn't call `delete` but I can't fathom why you'd want to do this.
Mark B
+3  A: 

If you only want your own delete to call your overload, I would not overload the delete operator but instead make a custom method like DeleteMyObject which would call the original delete and then create a macro to call this function and replace all your deletes with this macro.

Like

#define DELETE_MY_OBJECT(obj) DeleteMyObject(obj, __FILE__, __LINE__)

and the method could look like

void DeleteMyObject(void* obj, char* file, char* line)
{
    // Log delete
    ...

    delete obj;
}

then in your code

MyObj* obj = ...
...
DELETE_MY_OBJECT(obj);
Eric Fortin
i already have a code and cannot change in the code, i can just add macros and invoke function. Thats why i had to do this.
max_dev