max_dev
max_dev

Reputation: 161

Overloading Delete Operator in c++

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?

Upvotes: 3

Views: 1861

Answers (2)

Eric Fortin
Eric Fortin

Reputation: 7603

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);

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361585

map and stack are explicitly calling delete yourObject under the hood, for most definitions of "explicit"—that's why your delete operator is getting called. Those deletes are no less legitimate than ones in your code.

How do you get the file name and line number, by the way? Beware that __FILE__ and __LINE__ probably won't work. Those will return the file name and line number of the line number they're found on, meaning you'll get the location of your delete method, not the location of the caller.

To get the behavior you want, both only logging "explicit" deletes and tracking their location, you'll need to replace the deletions you want to log with macro calls. In that case you don't need to override delete. For example:

#define DELETE(p) \
    do { \
        std::cout << __FILE__ << ":" << __LINE__ << ": " << p << std::endl; \
        delete p; \
    }

Upvotes: 1

Related Questions