Created
December 29, 2010 21:10
-
-
Save deepfryed/759072 to your computer and use it in GitHub Desktop.
c++ new/delete operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ./overload | |
>> Person | |
>> operator new | |
>> Person | |
>> ~Person | |
>> operator delete | |
>> ~Person |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
#include <cstdio> | |
using namespace std; | |
class Person { | |
public: | |
string name; | |
void* operator new(size_t n) { | |
printf(">> operator new\n"); | |
void *ptr = malloc(n); | |
if (!ptr) throw "OutOfMemoryError: cannot allocate memory"; | |
return ptr; | |
} | |
void operator delete(void* ptr) { | |
printf(">> operator delete\n"); | |
if (ptr) free(ptr); | |
} | |
Person(string s) { | |
printf(">> Person\n"); | |
name = s; | |
} | |
~Person() { | |
printf(">> ~Person\n"); | |
} | |
}; | |
int main() { | |
// stack | |
Person p1("james"); | |
// heap | |
Person *p2 = new Person("jimmy"); | |
delete p2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment