Sign in to follow this  
n3Xus

[C++] overloaded new operator problems

Recommended Posts

n3Xus    951
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:
[code]
// placement new
T* t=new(__LINE__,__FILE__)(&m_data[i])T;
[/code]

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 [img]http://public.gamedev.net/public/style_emoticons/default/laugh.gif[/img]").

Share this post


Link to post
Share on other sites
How about something like this :

[code]
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));
}
[/code]

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this