Sunday, October 23, 2011

operator new and new operator and overloading

1. new and delete are very complex, it is worth to do some research on it.
first thing I want to mention is about operator new and new operator. 
new operator is a keyword in the C++ just like sizeof, you can do nothing on it(you cannot try to change them). In fact, when you write the expression
Bob* bob=new Bob();
 C++ do 3 steps for you.
First, they allocate a block of memory for you(actually, you will find that this step is invoke the function new operator) , then invoke the constructor, finally, they return you a pointer. 

We cannot change the whole operator new, but we can do something for each step.

for first step, you can overload the new operator, this is an operator just like + operator,you can overload this operator.
So you can do this in your code:
void *operator new(size_t size); 
 //this is most basic overloading for new operator, placement new 
//and something else will come soon in next tips
for the second step you can override you constructor.

third step is nothing but return a pointer. 

2.Delete operator also does the similar things. But the destructor is invoked before the delete operator. One thing you should never forget, if you overload the new operator, please never forget your delete operator! because who knows what you did in your new operator.

let's look some codes here to know what happened.

using namespace std;
class Bob{
 int a;
 int c;
 Bob(int a_,int c_){
  cout<<"Bob constructor"<<endl;

 void *operator new(size_t size){
  void* p=malloc(size);
  cout<<"Bob new"<<endl;
  return p;
 void operator delete(void* ptr){
  cout<<"Bob died in delete"<<endl;
  cout<<"Bob is killed in destructor"<<endl;

void main(int argc,char* arg[]){
 Bob* bob=new Bob(1,2);
 delete bob;
 char a;

Bob new
Bob constructor
Bob is killed in destructor
Bob died in delete

No comments:

Post a Comment