overriding global new

J

john smith

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 ::eek:perator new( my_size );

}
 
I

Ian McCulloch

john said:
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 ::eek:perator 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top