在GCCAVR C++中如何重載new,delete
void * operator new (size_t size)
{
void * ptr;
ptr = malloc(size);
if (!ptr) return ptr;
memset(ptr, '\0', size);
return ptr;
}
void operator delete(void * obj)
{
free(obj);
}
應用:
inline String::String(const char * str)
{
if (!str) {
_size = 0;
_string = 0;
}
else {
_size = strlen(str);
_string = new char(_size + 1);
strcpy(_string, str);
}
}
inline String & String:perator = (const char * s)
{
if (!s) {
_size = 0;
delete _string;
_string = 0;
}
else {
_size = strlen(s);
delete _string;
if (_size == 0) _string = 0;
else {
_string = new char(_size + 1);
strcpy(_string, s);
}
}
return *this;
}
|
|