C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

overriding global new

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
john smith
Guest





PostPosted: Fri Jan 28, 2005 2:50 am    Post subject: overriding global new Reply with 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

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





PostPosted: Fri Jan 28, 2005 2:58 am    Post subject: Re: overriding global new Reply with quote



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
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
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


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.