By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,134 Members | 1,742 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,134 IT Pros & Developers. It's quick & easy.

overriding global new

P: n/a
I am trying to override global new.

Yes, I know this is not a good idea, but I want to do it anyway. Notice
that I am not trying to override new in a class.

Any suggestions? I thought the below would work but it just goes into a
recursive call (infinite loop)

Is this not possible? ummm

Many thanks to any suggestions.

#include <iostream>

class car {

public:

car()

{

std::cout << "car " << std::endl;

}

int type;

};

int main()

{

car my_car;

car* p_my_car = new car();

return 0;

}

void* operator new( size_t my_size)

{

std::cout << "now grabbing some memory" << std::endl;

return ::operator new( my_size );

}
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
john smith wrote:
I am trying to override global new.

Yes, I know this is not a good idea, but I want to do it anyway. Notice
that I am not trying to override new in a class.

Any suggestions? I thought the below would work but it just goes into a
recursive call (infinite loop)

Is this not possible? ummm

[...]
void* operator new( size_t my_size)

{

std::cout << "now grabbing some memory" << std::endl;

return ::operator new( my_size );

}


Your global operator new is calling itself. I guess you meant to call the
'default' operator new instead? I don't think you can do that, but instead
you can use malloc. Also, you need to be *very* careful what you call
inside operator new. Any kind of C++-style IO or string handling is likely
to do some internal memory management, which may in turn .... call operator
new! Indeed, that is quite likely with your std::cout << "now grabbing
some memory" << std::endl; line. You can do C-style IO though. Try:

#include <cstdio>

void* operator new(size_t size)
{
std::printf("now grabbing some memory\n");
return malloc(size);
}

HTH,
Ian McCulloch

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.