 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
john smith Guest
|
Posted: Fri Jan 28, 2005 2:50 am Post subject: overriding global new |
|
|
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 );
}
|
|
| Back to top |
|
 |
Ian McCulloch Guest
|
Posted: Fri Jan 28, 2005 2:58 am Post subject: Re: overriding global new |
|
|
john smith wrote:
| Quote: | 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
|
[...]
| Quote: | 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
void* operator new(size_t size)
{
std::printf("now grabbing some memoryn");
return malloc(size);
}
HTH,
Ian McCulloch
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|