[C++] overloaded new operator problems

Started by
0 comments, last by BradBobak_68669 12 years, 9 months ago
Hello,

I decided to overload the new, new[],... operators in my classes so I can log the file and line at which they were called so I can easier track memory allocations/leaks.


Now the problems is in my stack and array classes (and other template container classes which allocate memory):

If I use them with one of my classes which has the new,new[],... operators overloaded it works fine.

But if I use it with the standard c++ data types (int,float,...) I can't allocate them, since no overloaded new operator matches the arguments of the new(__LINE__,__FILE__) operator (or others like placement new).



Example of stack code:

// placement new
T* t=new(__LINE__,__FILE__)(&m_data)T;


So I'm out of good ideas on how to make this work. If I replace new(__LINE__,__FILE__) with new I loose memory logging ability.
One solution is to make a separated stack for standard data types in which the default new is used.

How do you handle stuff like this?
What do you suggest?
Any comments on this design (good,bad) are obviously welcome (just don't post stuff like "don't reinvent the wheel with your own containers laugh.gif").
Advertisement
How about something like this :


template < class X >
X *log(char const *file_, unsigned line_, X *where_)
{
try
{
log_new(file_, line_);
}
catch (...)
{
delete where_;

throw;
}

return where_;
}

#define LOGGED_NEW(type) log(__FILE__, __LINE__, new type)

struct y { y(int x) { } };

int main()
{
int *i = LOGGED_NEW(int);
y *yy = LOGGED_NEW(y(5));
}


Of course, this won't work with arrays, but you could make a LOGGED_NEW_ARRAY, log_array for that.

This topic is closed to new replies.

Advertisement